为什么TreeSet抛出ClassCastException? [英] Why does TreeSet throw a ClassCastException?
问题描述
我正在尝试将两个 Employee对象添加到TreeSet中:
I am trying to add two 'Employee' objects to a TreeSet:
Set<Employee> s = new TreeSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));
但是它抛出ClassCastException:
But it throws a 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)
但是如果我仅向TreeSet添加一个对象:
But if I add only one object to the TreeSet:
Set<Employee> s = new TreeSet<Employee>();
s.add(new Employee(1001));
或者如果我改用HashSet:
Or if I use a HashSet instead:
Set<Employee> s = new HashSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));
然后成功。
推荐答案
任一 Employee
必须实现 可比较
,或者您需要在创建 时提供比较器
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屋!