How does TreeSet sort elements when it stores objects and not wrapper classes?

When storing custom objects in a TreeSet, the set must know how to compare those objects to maintain its sorted order. It determines the ordering either through the Comparable interface implemented by the object class or through a Comparator supplied when the TreeSet is created. Without a comparison mechanism, TreeSet cannot organize the elements and will throw a runtime exception.

Key Points: • If the class implements Comparable, TreeSet uses the compareTo() method for natural ordering. • A custom Comparator can be provided to define alternative sorting logic without modifying the class. • TreeSet relies on comparison results for both sorting and detecting duplicate elements.

Example: Consider an Employee class. If employees should be sorted by salary or name, TreeSet needs comparison logic. The compareTo() method or a Comparator tells TreeSet how to arrange Employee objects in ascending or descending order.

Code Example:

import java.util.TreeSet;

class Employee implements Comparable<Employee> {

    private int id;

    public Employee(int id) {
        this.id = id;
    }

    @Override
    public int compareTo(Employee other) {
        return Integer.compare(this.id, other.id);
    }

    @Override
    public String toString() {
        return "Employee ID: " + id;
    }
}

public class Main {
    public static void main(String[] args) {

        TreeSet<Employee> employees = new TreeSet<>();

        employees.add(new Employee(103));
        employees.add(new Employee(101));
        employees.add(new Employee(102));

        System.out.println(employees);
    }
}

Interview Tip: A concise interview answer is: TreeSet sorts custom objects using the compareTo() method of the Comparable interface or a Comparator provided during TreeSet creation. If neither is available, TreeSet cannot determine the order of elements and throws a ClassCastException at runtime.