SCJP 6.0
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
This is correct.The point of using the comparator & comparable interface is to sort objects in collections. Right?
nope, hash code and equals play role in searching not in sorting. As you can see in the below code, equals and hash code has not been overridden still is sorts the ArrayList well.Don't the hashcode/equals methods play a role in sorting in generic collections
Do you still need to override the hashcode/equals method for the class which implements the comparator/comparable interfaces?
Sometimes I see classes which implement these interfaces, override the appropriate compareTo/compare methods.
Then I see the those classes which implement these interfaces put in as generic types for collections such as TreeSet.
But I don't see where it indicates overriding the hashcode and equals methods.
Regards
Salil Verma
Anushree Acharjee wrote:But the following code makes me wonder whats happening
SortedSet wrote:Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
Anushree Acharjee wrote:So it means,contrary to as Salil explained, we need not to override equals() an hashCode() methods even when we are searching TreeSet or TreeMap. For sorting we need compareTo/compare method implementation. equals() and hashCode() do not come into the picture at all when dealing with TreeSet and TreeMap.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |