Creating TreeSet with Natural Ordering
What you'll learn: How to create TreeSet instances that automatically sort elements using their natural ordering.
When you create a TreeSet without specifying a custom comparator, it relies on natural ordering—the default sorting logic built into Java's standard types. For this to work, the elements must implement the Comparable interface, which defines how objects of that type compare to each other.
How Natural Ordering Works
Think of natural ordering like alphabetizing books by title or arranging numbers from smallest to largest. Java already knows how to do this for common types like String (alphabetical order) and Integer (numerical order).
When you add elements to a TreeSet using natural ordering, the TreeSet automatically consults each element's compareTo method to determine where it belongs in the sorted structure.
Creating TreeSet with String Elements
TreeSet<String> names = new TreeSet<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
// Iterating shows sorted order: Alice, Bob, Charlie
for (String name : names) {
System.out.println(name);
}
The strings are automatically sorted alphabetically because String implements Comparable.
Creating TreeSet with Integer Elements
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(15);
numbers.add(3);
numbers.add(42);
numbers.add(8);
// Iterating shows sorted order: 3, 8, 15, 42
for (Integer num : numbers) {
System.out.println(num);
}
Integers are automatically sorted numerically because Integer implements Comparable.
The Requirement
For natural ordering to work, your elements must implement Comparable. If they don't, you'll get a ClassCastException at runtime when the TreeSet tries to compare elements.
Key Takeaway: Creating a TreeSet with natural ordering is simple—just use the default constructor—but requires that your elements implement Comparable so the TreeSet knows how to sort them automatically.