Adding an element to a Treeset( was Plz clear My doubt ......)
kumaresan Natarajan
Greenhorn
Joined: Jul 23, 2005
Posts: 27
posted
0
I am tring to compile this programe it throws classcastException... Exception in thread "main" java.lang.ClassCastException at java.util.TreeMap.compare(TreeMap.java:1085) at java.util.TreeMap.put(TreeMap.java:463) at java.util.TreeSet.add(TreeSet.java:209) at SetTest.main(SetTest.java:6) Press any key to continue . . .
Thanks in advance Kumaresan [ July 28, 2006: Message edited by: Barry Gaunt ]
Thanks and Regards
kumaresan N
Stary Kapec
Ranch Hand
Joined: Dec 04, 2005
Posts: 81
posted
0
Hi,
You use TreeSet. It is a sorted set. Elements you put in it are compared with eath other to be placed in the right order (default would be natural order). So they must implement Comparable, moreover they must also be mutually comparable. Make the class Person comparable to solve the compilation problem. [ July 28, 2006: Message edited by: Jasiek Motyka ]
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
Please, Kumaresan, use a meaningful topic title and use tags to surround formatted code.
So, following on from Jasiek's post, you need a person class more or less like this:
Nishita Jain
Ranch Hand
Joined: Mar 30, 2006
Posts: 97
posted
0
"u forgot to implement the Comparable interface " Read this: java.util.TreeSet.TreeSet()
Constructs a new, empty set, sorted according to the elements' natural order. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add(Object) call will throw a ClassCastException.
[ July 28, 2006: Message edited by: Nishita Jain ] [ August 03, 2006: Message edited by: Nishita Jain ]
Nishita
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
hi, i modified your Person class and wrote like this now its running successfully.
Really? You can substitute your Person class for the original Person class and everything works? [ July 28, 2006: Message edited by: Barry Gaunt ]
kumaresan Natarajan
Greenhorn
Joined: Jul 23, 2005
Posts: 27
posted
0
Thanks Jasiek,Barry , Jain .....[ ]
Nishita Jain
Ranch Hand
Joined: Mar 30, 2006
Posts: 97
posted
0
Hello, i made changes in that code ya i agree that you cant replace that with original code...it was my mistake actually the focus point was "u forgot to implement the Comparable interface "..