Suppose I have a TreeMap with the Object type of the key and value. I want to put in a TreeMap Object :

 TreeMap<Object, Object> treeMap = new TreeMap(); treeMap.put(new Object(), new Object()); 

This code will generate an error:

 java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Comparable 

in the method

 final int compare(Object k1, Object k2) { return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2) : comparator.compare((K)k1, (K)k2); } 

which is inside the TreeMap .

I understand that if instead of Object take String , Integer or any other type, everything will be fine. Why doesn't it go with Оbject ?

    1 answer 1

    TreeMap is a collection that implements a red-black tree within itself. For this structure, it is imperative that the keys can be mapped to each other (bigger, smaller and equivalent). Therefore, in order to put some object inside, you must fulfill one of the following conditions:

    In your case, the Object class is attempted to result in Comparable , and the program crashes because it's impossible. String , Integer , Double, and many other classes from the standard library already implement this interface, and therefore with them everything works out.