为什么 TreeSet 会抛出 ClassCastException?
2022-09-02 03:52:12
我正在尝试将两个“员工”对象添加到树集:
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));
或者,如果我使用哈希集代替:
Set<Employee> s = new HashSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));
然后它成功了。为什么会发生异常,我该如何解决?