3

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.

asim
  • 73
  • 5
  • 1
    A tree set works by constructing a binary tree. In order to place objects in a binary tree, they need to be compared with the root node and each branch node they encounter (to see which side of the tree they need to go on). You can use a HashSet instead of a TreeSet if you'd rather implement `hash()` than `compareTo()`. – Green Cloak Guy Jan 04 '22 at 17:10
  • 1
    You can't put items in a `TreeSet` without knowing how to compare them. – Dave Newton Jan 04 '22 at 17:12
  • 1
    "*Why do objects put in a TreeSet have to implement the Comparable interface?*" - [They do not have to](https://ideone.com/3J1Kya). --- We need to provide some kind of order since [`TreeSet`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/TreeSet.html) implements [`SortedSet`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/SortedSet.html). – Turing85 Jan 04 '22 at 17:18

1 Answers1

3

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.

M. Justin
  • 14,487
  • 7
  • 91
  • 130
Paul
  • 3,009
  • 16
  • 33