Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equal() and hashCode() based on different fields?

Tags:

Is there any situation where it makes sense for a class to implement its equals() and hashCode() methods using a different set of the class fields?

I'm asking because I am puzzled by the Netbeans equals() and hashCode() generator, where you are asked to choose the fields to include in each method separately. I always end up selecting the same fields for both methods, but is there a situation where this is not the correct choice?

like image 739
Flavio Avatar asked Jan 20 '11 14:01

Flavio


People also ask

What is the relationship between hashCode () and equals () method in Java?

If two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects. But, it is not necessary that the hashCode() method will return the distinct result for the objects that are not equal (according to equals() method).

How do we implement hashCode () and equals ()?

Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.

How can I get same hashCode for different objects?

It is perfectly legal for two objects to have the same hashcode. If two objects are equal (using the equals() method) then they have the same hashcode.

How hashCode () and equals () method are used in HashMap?

In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.


1 Answers

Well, equals() must use all the fields used by hashCode(), as otherwise you could get different hash codes for equal objects. The reverse isn't true though - you could choose not to take account of one particular field when choosing the hash code. That way you could end up with the same hash code for two unequal objects which only differed by that "unused" field (as opposed to through natural collisions). You'd only want that in a situation where you knew collisions would be unlikely but where you were going to be hashing a lot. I imagine it's extremely rare :)

Another case would be where you had some sort of custom equality comparison - such as case insensitive string comparisons - where it's tricky or expensive to generate a hash code for the field. Again, this would lead to more likelihood of collision but would be valid.

like image 91
Jon Skeet Avatar answered Sep 28 '22 21:09

Jon Skeet