Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about Comparable and ClassCastException

 
Thomas Kennedy
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34375
346
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Thomas Kennedy
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic