0

Hi all,
When I run use to add second element in the tree set it shows java.lang.ClassCastException: could any one explain me why

import java.util.TreeSet;

public class Venus {
public String str;
public static void main(String[] args) {
Venus a =new Venus();
Venus b= new Venus();
a.str="obj1";
b.str="obj2";
TreeSet<Venus> set =new TreeSet<Venus>();
set.add(a);
set.add(b);
System.out.println(set.size());

 
 }

}
3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by ~s.o.s~
0

that is because Venus needs to implement the Comparable interface and have the compareTo(Object o) method of Comparable.

also b.str="obj1";

is a bad thing to do. I suggest declaring your variables as private and use setters and getters to get to the values or change them.

Edited by stultuske: OO design comment

0

thanks stultuskem,
ya I do setters and getters, I read that in one quiz when i add a.str="obj1";
it wont create problem
but when I add b.str="obj2"; it shows error

0

This is actually a bug/enhancement request which was fixed in JDK 7. Previously, adding a single non-comparable element to the TreeSet didn't cause any problem but as soon as a second one was added, it caused ClassCastException because the existing object was cast to Comparable to determine the location of the new one.

AFAIK, in JDK 7, adding a non-comparable element to TreeSet without a custom Comparator causes a runtime exception.

Edited by ~s.o.s~: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.