Issue
Why do objects put in a TreeSet have to implement the Comparable interface? I'm trying to create a TreeSet containing some objects of my own class but ClassCastException is thrown when I try to add objects in the set.
Solution
TreeSet
is an ordered implementation of Set
. Specifically, TreeSet
implements NavigableSet
and SortedSet
, both sub-interfaces of Set
.
Comparable
When TreeSet
's values are iterated they are returned in the order defined by the object's class. This can be useful when the objects in question have some natural concept of order - i.e. some values are 'less than' or 'more than' other values (e.g. dates).
In Java, the way to define the ordering of objects of a given class is by having that class implement Comparable
.
If you don't care about the ordering (which is often the case) you can use HashSet
instead.
Alternatively, if you care about the order in which elements were added (but not their 'natural' order) you can use LinkedHashSet
.
Comparator
Finally, you might sometimes be interested in a set with a guaranteed iteration order (which is not the order the elements were added) but which is not the natural order of the objects defined by compareTo
. When this happens you can use the constructor for TreeSet
which takes an explicit Comparator
. This conparator than defines the ordering (e.g. for iteration) for that specific map, which can be different from the natural order - if the objects have one, which they don't have to when using this constructor.
Answered By - Paul