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());

 
 }

}

Recommended Answers

All 3 Replies

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.

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.