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.
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.
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.
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?
Costs matter. Justice lies in processes not outcomes. Crime is caused by criminals.
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.
Costs matter. Justice lies in processes not outcomes. Crime is caused by criminals.
Do not meddle in the affairs of dragons - for you are crunchy and good with ketchup. Crunchy tiny ad:
a bit of art, as a gift, that will fit in a stocking