Reputation: 1385
What I understand from hashcode method for objects in Java: it is required to calculate the hashcode of objects which in turn is used to calculate the index / bucket location of the object in a hashed datastructure like hashMap.
So will it be correct to say that for a class that is not to be used along with a hashed datastructure doesnt need to have hashCode() method implemented in it? in other words is overriding the equals() method enough for non hashed datastructures?
Also please correct me if my assumption is wrong .
Upvotes: 0
Views: 62
Reputation: 308031
In theory, you are correct: if you know that your object will never be used in any way that requires the hash code, then not implementing hashCode
will not cause anything bad to happen.
In practice there are reasons not to rely on this fact:
hashCode
then, things can go bad.equals
and you don't implement hashCode
then you are almost certainly breaking the contract of hashCode
that requires it to be consistent to equals
. If your code breaks a contract that other code depends on, then that other code can silently fail in unexpected/weird ways.equals
anyway and if you do that generating the appropriate hashCode
at the same time is no extra effort.Note that all of this assumes you even want to implement equals
: If you don't care about equality of an object entirely (which is actually very common, not every type needs a specific equality definition), then you can just leave equals
and hashCode
out of your code and it's all conforming ('though your type might not match the "intuitive" equality definition of your type then).
Upvotes: 6