Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TreeSet is an ordered implementation of Set. 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.

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading