• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

TreeSet's add() method runtime error

 
Xiao Hu
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, ranchers:
Why the following codes get a runtime error?
import java.util.*;
public class CollectionTest01 {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(new Object());
ts.add(new Object());
}
}
error: java.lang.ClassCastException
I know that when an element is added to the TreeSet, the element to add is compared with each element in the Treeset to determine the position within the set. But why comparing 2 "Object"s cause a ClassCastException? I thought only comparing different type of objects would throw this exception.
 
Ek Chotechawanwong
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Xiao Hu
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ek
I just created a new class simply implementing Comparable.
Now everything is fine when I add this new object to TreeSet.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic