Why does TreeSet throw a ClassCastException?

Either Employee has to implement Comparable, or you need to provide a comparator when creating the TreeSet. This is spelled out in the documentation for 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 … Read more

Hashset vs Treeset

HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet. HashSet the class offers constant time performance for the basic operations (add, remove, contains and size). it does not guarantee that the order of elements will remain constant over time iteration … Read more