jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes TreeSet's add() method runtime error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "TreeSet Watch "TreeSet New topic

TreeSet's add() method runtime error

Xiao Hu

Joined: Jan 28, 2004
Posts: 9
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

Joined: Jun 23, 2002
Posts: 7
Hi Xiao,
Interesting question.
Please let me try.
In order to add an object into a SortedSet or SortedMap, that object needs to implement
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

Joined: Jan 28, 2004
Posts: 9
Thanks Ek
I just created a new class simply implementing Comparable.
Now everything is fine when I add this new object to TreeSet.
I agree. Here's the link: http://aspose.com/file-tools
subject: TreeSet's add() method runtime error
It's not a secret anymore!