Java – why does TreeSet throw ClassCastException
•
Java
In the following code, I try to add two employee objects
Set<Employee> s = new TreeSet<Employee>(); s.add(new Employee(1001)); s.add(new Employee(1002));
But the result is 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)
But if I change
Set<Employee> s = new TreeSet<Employee>(); s.add(new Employee(1001));
or
Set<Employee> s = new HashSet<Employee>(); s.add(new Employee(1001)); s.add(new Employee(1002));
Then success is no exception I didn't do any class conversion in the above code Please help me find out the reason and put forward my solution
Solution
Employees must implement comparable, or provide a comparator when creating TreeSet
This is described in detail in the sortedset documentation:
If you do not meet these requirements, the sort set will not know how to compare its elements and will not work properly
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码