TreeSet
is implemented on top of TreeMap
. So TreeSet.add()
calls to TreeMap.put(Object, Object)
method. Please see the below:
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); //this is the culprit
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
……………
……………
……………
}
Now as the root
is null
so the flow will go inside the if (t == null) {
hence calls compare(key, key)
.
final int compare(Object k1, Object k2) {
return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
: comparator.compare((K)k1, (K)k2);
}
As inside the compare
method it is typecasting k1, k2
Comparable
and your class does not implement Comparable
hence the exception:
Exception in thread "main" java.lang.ClassCastException:
.
This code is as per JDK 1.7.