Sobes.tech
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:

  1. Natural ordering of elements

    • Elements must implement the Comparable interface.
    • Sorting is based on the compareTo method of the elements.
  2. Custom comparator (Comparator)

    • When creating a TreeSet, you can pass an object that implements the Comparator interface.
    • Sorting will follow the logic defined in this comparator.

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.