aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question 10 Chapter 7 : K and B Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question 10 Chapter 7 : K and B" Watch "Question 10 Chapter 7 : K and B" New topic
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
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question 10 Chapter 7 : K and B