1

I know that implementing/overriding equals() without also overriding hashCode() violates the equals/hashCode contract.

But what if a class implements only hashCode() and not equals()?

Bohemian
  • 365,064
  • 84
  • 522
  • 658
Arun Raaj
  • 1,520
  • 1
  • 15
  • 19

2 Answers2

3

If a class has only hashCode() then it's not a problem: Objects that are equal() will have the same hashCode().

This is because equals() will fall back to Object's implementation, which is identity, which will of course give the same hashCode()

Bohemian
  • 365,064
  • 84
  • 522
  • 658
0

If the object is the same, it must have the same hashCode.
If the object is different, it doesn't have to have a different hashCode.

so when hashCode is the same, it's not necessarily the same object.
But when hashCode is different, it must not be the same object.

Destiny.Wang
  • 169
  • 8