java - 为什么 TreeSet 抛出 ClassCastException?

标签 java exception collections set treeset

我正在尝试将两个“Employee”对象添加到 TreeSet:

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

但是它抛出一个 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 添加一个对象:

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

或者如果我改用 HashSet:

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

那么就成功了。为什么会发生异常,我该如何解决?

最佳答案

要么 Employee 必须实现 Comparable , 或者你需要 provide a comparator创建 TreeSet 时.

这在 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.

如果您不满足这些要求,有序集将不知道如何比较其元素,也将无法运行。

关于java - 为什么 TreeSet 抛出 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15943031/

相关文章:

java - 如何使用私有(private)构造函数从类创建对象?

java - 为什么 List<type> 在编译和执行时吸收非类型元素?

c++ - 正确尝试/捕获无序映射异常

java - query.getSingleResult() 与 query.getResultList().get(0)

java - Struts2 集合验证

java - 按时间间隔测试代码

java - 如何在 Assertj Collection of Set 中验证

java - 什么是 Java 中的时间对象?

sql-server - 如何识别表中的哪条记录已引发错误

Laravel 合并集合失败?