日期:2014-05-20  浏览次数:20770 次

TreeSet排序问题
import   java.util.HashSet;
import   java.util.Iterator;
import   java.util.Scanner;
import   java.util.Set;
import   java.util.TreeSet;
import   java.io.IOException;
import   java.util.Scanner;

public   class   TestPeople   {

public   static   void   main(String[]   args)   {
                    Set   set   =   new   TreeSet();
        People   s1   =   new   People( "draglong ");
        People   e2   =   new   People( "jack ");
        People   e3   =   new   People( "smith ");
        set.add(s1);
        set.add(e2);
        set.add(e3);
        Iterator   iter   =   set.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
      }
            }
}

public   class   People   {

private   String   Str;

public   People(String   str)   {
this.Str   =   str;
}
}

      我用Eclipse运行时报错。信息为:
        Exception   in   thread   "main "   java.lang.ClassCastException:   cn.edu.my.People
at   java.util.TreeMap.compare(TreeMap.java:1093)
at   java.util.TreeMap.put(TreeMap.java:465)
at   java.util.TreeSet.add(TreeSet.java:210)
at   cn.edu.my.TestPeople.main(TestPeople.java:42)
      也就是set.add(s1);
        set.add(e2);
        set.add(e3);出错了。请问错在哪儿了,怎么改?如果我要输入姓名,年龄,班级后要排序又该怎么办?是不是要将HashSet中的add()重写阿?

------解决方案--------------------
public class TestPeople {

private String Str;

public static void main(String[] args) {
Set set = new TreeSet();
String s1 = People.People( "draglong ");
String e2 = People.People( "jack ");
String e3 = People.People( "smith ");
set.add(s1.toString());
set.add(e2);
set.add(e3);
Iterator iter = set.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
}
}
}


public class People {


public static String People(String str) {

return str;
}
}
------解决方案--------------------
public class Test
{
public static void main(String[] args)
{
People p=new People( "hello ",1);
java.util.Set set=new java.util.TreeSet(p);
People s1 = new People( "draglong ",12);
People e2 = new People( "jack ",15);
People e3 = new People( "smith ",13);
set.add(s1);
set.add(e2);
set.add(e3);
java.util.Iterator i=set.iterator();
while(i.hasNext())
System.out.println(i.next());
}
}
class People implements java.util.Comparator
{
private String name;
private int age;
public People(String name,int age)
{
this.name=name;
this.age=age;
}
public int getAge()