GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Question about Comparable and ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question about Comparable and ClassCastException" Watch "Question about Comparable and ClassCastException" New topic
Author

Question about Comparable and ClassCastException

Thomas Kennedy
Ranch Hand

Joined: Jan 20, 2008
Posts: 137
My study notes contain the following:

If the objects you add to a Set do not implement Comparable you will get a ClassCastException when you add the second object. The JVM is trying to cast this object to a Comparable in order to compare it to the first one.


Assuming this note is correct, why does the object first have to be cast to Comparable?


Costs matter. Justice lies in processes not outcomes. Crime is caused by criminals.
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30586
    
154

Thomas,
Set needs to know whether the object is already in the set. To figure this out, it wants to call the compare method. Since this method is defined on the Comparable interface, Set needs to cast the object first. This casting makes the compare method available.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Your study notes are incorrect though. This limitation only holds for TreeSet, and only if you have not used the constructor that takes an Comparator. HashSet and LinkedHashSet use hashCode and equals instead of compareTo, and the Comparator will have precedence over using compareTo.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Thomas Kennedy
Ranch Hand

Joined: Jan 20, 2008
Posts: 137
Originally posted by Jeanne Boyarsky:
Thomas,
Set needs to know whether the object is already in the set. To figure this out, it wants to call the compare method. Since this method is defined on the Comparable interface, Set needs to cast the object first. This casting makes the compare method available.


Jeanne,

Is it correct to say that the set needs to do this cast because at runtime it sees only an Object?
Thomas Kennedy
Ranch Hand

Joined: Jan 20, 2008
Posts: 137
Rob,

Thank you, I have corrected that. When this is all done my book & notes are most likely going to some soldier overseas so it wouldn't do to include all the errors.
 
Consider Paul's rocket mass heater.
 
subject: Question about Comparable and ClassCastException