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