| Author |
Question 10 Chapter 7 : K and B
|
jose chiramal
Ranch Hand
Joined: Feb 12, 2010
Posts: 266
|
|
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Comparable
I tried compiling the above prog but got this exception :
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Comparable
|
 |
Harpreet Singh janda
Ranch Hand
Joined: Jan 14, 2010
Posts: 317
|
|
You need to add object which implements the comparable interface of. This is the default implementation of the add method.
Below is the excerpt from API
|
 |
Rahul Manikuntla
Greenhorn
Joined: Apr 07, 2010
Posts: 11
|
|
|
Yes, TreeSet is sorted collection and must have elements that implement compareTo() from interface Comparable. That is how TreeSet will know where to add() the new elements.
|
SCJP 5.0
|
 |
Rajeev Rnair
Ranch Hand
Joined: Mar 22, 2010
Posts: 308
|
|
Rahul Manikuntla wrote:Yes, TreeSet is sorted collection and must have elements that implement compareTo() from interface Comparable. That is how TreeSet will know where to add() the new elements.
Exactly! In
you are adding a String and an Object o. String, Wrappers, Date classes implement Comparable by default. But cannot add a plain "Object o" which hasn't implemented Comparable.
|
SCJP6, SCWCD5, OCP-JBCD5, OCE-JWSD6 OCE-JPAD6 , OCM-JEA5 1,OCM-JEA5 2,3 - Brainbench certifications: J2EE, Java2, Java2-NonGUI, JSP, SQL2000 Admin, SQL2000 Programming , Brainbench certified Java Programmer, Computer Programmer, Web Developer, Database Administrator
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9191
|
|
It is not necessary that the objects that we add to a TreeSet implement Comparable. If we use a Comparator, then we can add elements to the TreeSet which don't implement Comparable. Eg:-
The rule is, the elements that we add to the TreeSet must be comparable to each other...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
 |
|
|
subject: Question 10 Chapter 7 : K and B
|
|
|