Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Comparable and TreeSet

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.

like image 707
asim Avatar asked Apr 29 '26 12:04

asim


1 Answers

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 comparator than defines the ordering (e.g. for iteration) for that specific set, which can be different from the natural order - if the objects have one, which they don't have to when using this constructor.

like image 52
Paul Avatar answered May 01 '26 00:05

Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!