I was just wondering if it was a good idea to override equals
and hashCode
for mutable collections. This would imply that if I insert such a collection into a HashSet
and then modify the collection, the HashSet
would no longer be able to find the collection. Does this imply that only immutable collections should override equals
and hashCode
, or is this a nuisance Java programmers simply live with?
You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object. hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.
StringBuilder/ StringBuffer does not override equals() and hashCode() method.
we should always override hashCode() method whenever we override equals() method.
If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.
You should override equals
and hashCode
if your class should act like it were a value type. This usually is not the case for collections.
(I don't really have much Java experience. This answer is based on C#.)
The problem of deep and shallow equals is bigger than Java; all object oriented languages have to concern themselves with it.
The objects that you add to the collection should override equals and hash code, but the default behavior built into the abstract implementation of the collection interface suffices for the collection itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With