Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java hashCode() method override is not needed if we don't use hashmap or hashset

My co-worker was overriding the equals() method. My response was, have you also overridden the hashCode() method? His response was because we won't use hash map or hash set, it shouldn't really matter if we override hashCode(). Is that correct?

like image 664
user1739658 Avatar asked Feb 08 '13 20:02

user1739658


People also ask

What happens if we don't override hashCode in HashMap?

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.

Is it necessary to override hashCode and equals method in HashMap?

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.

What happens if we do not override hashCode () and equals () in HashSet?

Overriding only equals() method without overriding hashCode() causes the two equal instances to have unequal hash codes, which violates the hashCode contract (mentioned in Javadoc) that clearly says, if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two ...

Can we override hashCode method in Java?

So all java classes have the hashcode() method by default. We can override these methods in our classes. Hashcode() is a method to return an unique integer which is used for indentifying the bucket where this object will be stored for hashing based collections like HashMap.


1 Answers

Yes he is factually right - however, if you need to put your objects in a hash-based collection one day, you will have to add hashcodes everywhere, which can be annoying + on that day you might implement your hashcode incorrectly (i.e. not consistent with equals) because you miss some subtlety in the equals method...

Considering that most IDEs provide an auto equals/hashcode generation feature, I see little reason not to create both.

Another way to look at it is: when you override a method from a parent class, you should follow the contract defined by that parent class. In the case of Object, the javadoc of equals is pretty clear:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

So unless you have a real design reason not to override hashcode, the default decision should be to follow the parent class contract and override neither or both.

like image 110
assylias Avatar answered Nov 03 '22 18:11

assylias