为什么TreeSet抛出ClassCastException [英] Why does TreeSet throws ClassCastException
问题描述
在下面的代码中,我试图添加两个员工对象
In below code I am trying to add two employee object
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));
然后结果是成功没有异常。我没有在上面的代码中做任何类转换活动。请帮助我找出原因并建议我的解决方案。
Then result is success there is no exception. I am not doing any class casting activity in above code. Please help me to find out the cause and suggest me the solution.
推荐答案
员工
必须实施 可比较的
,否则您需要在创建 <$ c $时提供比较器 c> TreeSet 。
Either Employee
has to implement Comparable
, or you need to provide a comparator when creating the TreeSet
.
这在 SortedSet
:
插入到排序集合中的所有元素必须实现
Comparable
接口(或被指定的比较器接受)。此外,所有这些元素必须相互比较:e1.compareTo(e2)
(或comparator.compare(e1,e2)
)不得为任何元素e1
和e2 $ c抛出
ClassCastException
$ c>在排序集合。尝试违反此限制将导致冒犯方法或构造函数调用抛出ClassCastException
。
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)
(orcomparator.compare(e1, e2)
) must not throw aClassCastException
for any elementse1
ande2
in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw aClassCastException
.
如果不满足这些要求,排序集将不知道如何比较其元素,并且将无法正常工作。
If you don't fulfil these requirements, the sorted set won't know how to compare its elements and won't be able to function.
这篇关于为什么TreeSet抛出ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!