TreeSet实现了SortedSet接口,可以对集合中的对象进行排序,但是在使用TreeSet时要注意一点,那就是要给TreeSet传递一个比较器,也就是指定比较规则,否则的话,它就不知道谁大谁小,也就不能排序了。此时它会报一个ClassCastException的异常。
jdk1.6文档里add方法关于这个异常是这样描述的:
Throws:
ClassCastException - if the specified object cannot be compared with the elements currently in this set
翻译:ClassCastException - 如果指定的对象不能与当前在此集合中的元素进行比较
public class TreeSetTest
{
public static void main(String[] args)
{
MyComparator comparator = new MyComparator();
// TreeSet<Student> set = new TreeSet<Student>(comparator);
// 错误的代码,少了比较器,运行则报下面的异常。
TreeSet<Student> set = new TreeSet<Student>();
Student s1 = new Student(50);
Student s2 = new Student(70);
Student s3 = new Student(40);
set.add(s1);
set.add(s2);
set.add(s3);
System.out.println(set);
}
}
class Student
{
int score;
public Student(int score)
{
this.score = score;
}
@Override
public String toString()
{
// TODO Auto-generated method stub
return String.valueOf(this.score);
}
}
class MyComparator implements Comparator<Student>
{
@Override
//按分数高低比较,int为返回负数、零、整数,这里我写的不咋好,但意思一样
public int compare(Student o1, Student o2)
{
// TODO Auto-generated method stub
int result = 0;
if(o1.score > o2.score)
{
result = 1;
}else
{
result = -1;
}
return result;
}
}
错误的运行结果:
Exception in thread "main" java.lang.ClassCastException: com.shengsiyuan2.Student cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1294)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at com.shengsiyuan2.TreeSetTest.main(TreeSetTest.java:17)
解决办法:
把 TreeSet set = new TreeSet(); 改成:TreeSet set = new TreeSet(comparator);即可。