Course contentsShow
← Java
Lesson 1135 of 2,87026. Map ImplementationsFree lesson

Key Requirements: Comparable or Comparator

Why TreeMap keys must be comparable, and what happens when they're not (ClassCastException).

Key Requirements: Comparable or Comparator

You'll learn why TreeMap keys must be comparable and what error occurs when they're not.

Why TreeMap Keys Must Be Comparable

Unlike HashMap (which uses hash codes to organize keys), TreeMap builds a sorted tree structure. To maintain sorted order, TreeMap needs a way to compare any two keys and determine which comes first.

This means every key you put into a TreeMap must be comparable through one of two mechanisms:

  • Natural ordering: Keys implement the Comparable interface
  • Custom ordering: You provide a Comparator at TreeMap creation

Without either mechanism, TreeMap has no way to determine where in the tree structure to place a new key.

What Happens Without Comparability: ClassCastException

If you try to add a key that isn't comparable (and you didn't provide a Comparator), TreeMap throws a ClassCastException when it tries to compare keys internally:

class Person {
    String name;
    Person(String name) { this.name = name; }
}

TreeMap<Person, String> map = new TreeMap<>();
map.put(new Person("Alice"), "Developer");  // ClassCastException!
// Error: Person cannot be cast to java.lang.Comparable

The exception occurs because TreeMap internally tries to cast your key to Comparable to call compareTo(). When that cast fails, the operation crashes.

Think of It This Way

Imagine a librarian trying to shelve books alphabetically, but some books have no titles or labels. Without knowing how to compare them, the librarian can't determine where they belong on the shelf. TreeMap is that librarian—it must have a comparison rule.

Key Takeaway: TreeMap keys must either implement Comparable or you must provide a Comparator at construction; otherwise, ClassCastException will be thrown when comparing keys.