Junior — Middle
How are elements sorted in a TreeSet?
sobes.tech AI
Answer from AI
In Java, TreeSet is a set where elements are stored in sorted order. Sorting of elements in a TreeSet is primarily done in two ways:
-
Natural ordering of elements
- Elements must implement the
Comparableinterface. - Sorting is based on the
compareTomethod of the elements.
- Elements must implement the
-
Custom comparator (
Comparator)- When creating a
TreeSet, you can pass an object that implements theComparatorinterface. - Sorting will follow the logic defined in this comparator.
- When creating a
Example of using a comparator:
TreeSet<String> set = new TreeSet<>(Comparator.reverseOrder());
set.add("apple");
set.add("banana");
set.add("cherry");
// Elements will be sorted in reverse lexicographical order
If neither Comparable nor Comparator is provided, attempting to add an element that does not implement Comparable will result in a ClassCastException.