TreeSet

publicclass Tree

implements Comparator<Tree>

{

publicstaticvoid main( String args[] )

{

TreeSet<Tree> l =new TreeSet<Tree>();

for(int i = 0; i < 5; i++ )

{

l.add(new Tree());

}

}

publicint compare( Tree t, Tree t1 )

{

return 3;

}

}

When I run the above program I am ClassCastException. Why?

[1058 byte] By [jaaya] at [2007-10-3 6:51:50]
# 1
sory for my post.I got it, I did not specify the comparator in TreeSet Constructor
jaaya at 2007-7-15 1:42:52 > top of Java-index,Java Essentials,New To Java...
# 2

First of all, the program above does not compile, because you're missing import statements.

But to answer the question: Did you look at the error message? It says:

Exception in thread "main" java.lang.ClassCastException: Tree cannot be cast to java.lang.Comparable

at java.util.TreeMap.put(TreeMap.java:542)

at java.util.TreeSet.add(TreeSet.java:238)

at Tree.main(Tree.java:13)

Your class Tree must either (1) implement Comparable (not Comparator), or (2) you must pass an instance of a Comparator<Tree> to the constructor of TreeSet.

In case (1), the TreeSet will compare the objects by calling compareTo(...) on the objects; in case (2), the TreeSet will use the Comparator object that you passed to the constructor to compare the objects.

You can't mix those two approaches, which is what you're doing in your code above.

jesperdja at 2007-7-15 1:42:53 > top of Java-index,Java Essentials,New To Java...
# 3

ok I got it.

But just 1 query,

say I use TreeSet without implementing Comparable as well as by not using any Comparator.

So while adding elements in the TreeSet it calls the compareTo method on the object that is added and results in ClassCastException.

But my question is where is the compareTo method now since the class has not implemented Comparable.

jaaya at 2007-7-15 1:42:53 > top of Java-index,Java Essentials,New To Java...