Sobes.tech
Senior

Can any object be added to a TreeMap as a key?

sobes.tech AI

Answer from AI

In TreeMap in Java, keys must either implement the Comparable interface or a Comparator object must be provided when creating the TreeMap. This is necessary for the TreeMap to order the keys in a specific manner.

If an object does not implement Comparable and no Comparator is provided, attempting to add such a key will result in a ClassCastException at runtime.

Example:

TreeMap<String, Integer> map = new TreeMap<>();
map.put("apple", 1); // works because String implements Comparable

class MyKey {}
TreeMap<MyKey, Integer> map2 = new TreeMap<>();
map2.put(new MyKey(), 1); // will throw ClassCastException if no Comparator is provided

// Correct with a Comparator:
TreeMap<MyKey, Integer> map3 = new TreeMap<>(new Comparator<MyKey>() {
    public int compare(MyKey o1, MyKey o2) {
        // comparison logic
        return 0;
    }
});
map3.put(new MyKey(), 1); // now it works

Therefore, you cannot add any object as a key to a TreeMap without ensuring that the keys can be compared.