ClassCastException: When Elements Aren't Comparable
What You'll Learn
You'll discover why trying to add elements to a TreeSet that can't be compared causes a ClassCastException at runtime.
The Problem: TreeSet Needs to Compare
Remember that TreeSet maintains elements in sorted order using a red-black tree structure. To sort elements, TreeSet must compare them using compareTo() from the Comparable interface.
When you add an element that doesn't implement Comparable, or when you mix incompatible types, TreeSet can't perform the comparison it needs—and Java throws a ClassCastException.
When This Happens
Scenario 1: Non-Comparable Type
If you try adding objects of a class that doesn't implement Comparable, the first element succeeds (nothing to compare yet), but the second element triggers the exception because TreeSet tries to call compareTo() on something that doesn't have it.
Scenario 2: Mixing Incompatible Types
Even if both types are Comparable, you can't mix apples and oranges. Trying to add a String to a TreeSet already containing Integer objects will fail—String and Integer can't be compared to each other.
The Analogy
Think of TreeSet as a librarian arranging books alphabetically on a shelf. If you hand the librarian a book with no title, they can't file it. Similarly, if you mix English books with Chinese books that use different alphabetization systems, the librarian can't maintain one consistent ordering.
Runtime vs Compile-Time
This is a runtime exception, not a compile-time error. Java's generics can't enforce the Comparable requirement at compile time, so you only discover the problem when your code actually tries to insert the element.
Key Takeaway: TreeSet requires elements to be mutually comparable; adding non-comparable objects or mixing incompatible types throws ClassCastException at runtime.