求助:Treeset类中的简单问题!
程序如下:
import java.util.*;
class Person
{
private int javascore;
private String name;
Person(int j,String n)
{
this.javascore=j;
this.name=n;
}
public String toString()
{
return javascore+" "+name;
}
}
class Test
{
public static void main(String[] args)
{
Person p1=new Person(40,"Feng");
Person p2=new Person(90,"kaili");
Person p3=new Person(30,"zhanglian");
Person p4=new Person(80,"jay");
TreeSet ts=new TreeSet();
ts.add(p1);
ts.add(p2);
ts.add(p3);
ts.add(p4);
System.out.println(ts);
System.out.println();
}
}
问题:当我按如上代码运行时,出现如下错误:
D:\study\java\java\Treeset1>javac *.java
D:\study\java\java\Treeset1>java Test
Exception in thread "main"
java.lang.ClassCastException at java.util.TreeMap.compare(TreeMap.java:1085)
at java.util.TreeMap.put(TreeMap.java:463)
at java.util.TreeSet.add(TreeSet.java:209)
at Test.main(Treeset1.java:33)
D:\study\java\java\Treeset1>
但当我把ts.add(p2);
ts.add(p3);
ts.add(p4);都注释掉后,则程序能够运行!输出如下结果:
D:\study\java\java\Treeset1>javac *.java
D:\study\java\java\Treeset1>java Test
[40 Feng]
D:\study\java\java\Treeset1>
为什么会出现这样的结果?
顺便问一句,若实现按javascore成绩的升序排列,如何把 javascore的成绩提取出来进行比较?
(本人菜鸟,java刚入门,望高手指教!)
------解决方案--------------------TreeSet中的对象是要排序的