Hi Xiao,
Interesting question.
Please let me try.
In order to add an object into a SortedSet or SortedMap, that object needs to implement
java.lang.Comparable
interface (this will give you a sorted set according to the natural order, otherwise, you will need to supply a Comparator object into the TreeSet constructor.
If you look at the javadoc of TreeSet (its constructor and add() method), you will see the contract that its user must obey.
I believe the TreeSet/TreeMap implementor(JDK vendor), would usually downcast the provided argument of type Object to Comparable in order to use compareTo method. This will cause ClassCastException if it doesn't implement Comparable.
Chapter 11 of Khalid Mughal book (2nd edition) nicely explains this topic. Also, you may want to look at source code of TreeSet (which delegates its work to TreeMap). It's bundled with JDK.
Hope this could help.
Ek C.