Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should mutable collections override equals and hashCode?

Tags:

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?

like image 511
fredoverflow Avatar asked Mar 09 '11 14:03

fredoverflow


People also ask

Is it necessary to override hashCode and equals method?

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.

Which class does not override the equals () and hashCode () methods?

StringBuilder/ StringBuffer does not override equals() and hashCode() method.

What method should be overridden as well to ensure that food works correctly in a Hashtable?

we should always override hashCode() method whenever we override equals() method.

What happens if we don't override hashCode and equals?

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.


2 Answers

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#.)

like image 175
mgronber Avatar answered Nov 11 '22 12:11

mgronber


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.

like image 25
duffymo Avatar answered Nov 11 '22 11:11

duffymo