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 ?