java – 为什么TreeSet抛出ClassCastException

在下面的代码中,我试图添加两个员工对象
Set<Employee> s = new TreeSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));

但结果是java.lang.classCastException:

Exception in thread "main" java.lang.classCastException: Employee cannot be cast to java.lang.Comparable
    at java.util.TreeMap.put(TreeMap.java:542)
    at java.util.TreeSet.add(TreeSet.java:238)
    at MyClient.main(MyClient.java:9)

但是如果我改变了

Set<Employee> s = new TreeSet<Employee>();
s.add(new Employee(1001));

要么

Set<Employee> s = new HashSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));

那么结果是成功也不例外.我在上面的代码中没有做任何类的转换活动.请帮我找出原因,并提出我的解决方案.

解决方法

员工必须实施 Comparable,或者在创建 TreeSet时需要 provide a comparator.

SortedSet的文档中详细说明了这一点:

All elements inserted into a sorted set must implement the Comparable interface (or be accepted by the specified comparator). Furthermore,all such elements must be mutually comparable: e1.compareto(e2) (or comparator.compare(e1,e2)) must not throw a ClassCastException for any elements e1 and e2 in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException.

如果您不符合这些要求,排序集将不知道如何比较其元素,并且无法正常工作.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...