Sobes.tech
Junior — Middle

How is the sorting of elements implemented in TreeSet and how does it work?

sobes.tech AI

Answer from AI

TreeSet in Java is implemented based on a red-black tree — a balanced binary search tree. Elements in TreeSet are stored in sorted order, which is determined either by the natural ordering of the elements (via the Comparable interface) or by a comparator passed to the TreeSet constructor.

When adding an element, TreeSet inserts it into the tree to maintain order and balance. As a result, search, insertion, and deletion operations are performed in O(log n).

Example:

TreeSet<String> set = new TreeSet<>();
set.add("banana");
set.add("apple");
set.add("cherry");

for (String fruit : set) {
    System.out.println(fruit);
}
// Output:
// apple
// banana
// cherry

Thus, TreeSet provides automatic sorting and quick access to elements.