Reputation: 9232
I am exploring the various methods, operations and prerequisites of the most common Java collections and I am a little bit confused. I would be very grateful if somebody could clarify the following topics:
1) Is the implementation of the methods equals
and hashCode
absolutely required, in order for a TreeSet
and a TreeMap
to work properly, as it is in HashMap
? What are the potential implications of not implementing the previous methods? I am making currently use of a TreeMap and a TreeSet (of custom class Objects) and they work fine so far, just by implementing Comparable
and its method compareTo
, ommiting equals
and hashCode
.
2) When impelmenting in a class equals
, hashCode
or even the interface Comparable
, is it sufficient for all derived classes to work properly in collections according those methods without new definition and implementantion? I have the impression that the former is right, since the given methods belong to the derived classe as well. What is finally true?
Upvotes: 1
Views: 1588
Reputation: 533482
Is the implementation of the methods equals and hashCode absolutely required, in order for a TreeSet and a TreeMap to work properly, as it is in HashMap?
no.
What are the potential implications of not implementing the previous methods?
none.
When impelmenting in a class equals, hashCode or even the interface Comparable, is it sufficient for all derived classes to work properly in collections according those methods without new definition and implementantion?
Yes, making "work properly" isn't as simple as it sounds. Generally you want the keys or element to all the same type. It rarely a good idea to mix their types.
For TreeMap and TreeSet you only need to implement Comparable + compareTo OR a Comparator + compare.
Upvotes: 2