我正在尝试将两个“员工”对象添加到 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));
然后就成功了。为什么会发生异常,我该如何解决?