-3

[Core java programming] says if I overrides Object.equals(), then I should override Object.hashCode() at the same time.

This is quite odd to me, if I don't override hashCode() at the same time, is there any possibility that something wrong could happen in logic?

Would you help to give such an example to indicate?

Thanks a lot.

Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • You'll break `HashSet` and `HashMap` - if equal objects can have different hash codes, they can end up in a `HashSet` twice, which isn't what you want in a `Set`. – Dawood ibn Kareem Jan 07 '19 at 10:37
  • I would have a look at existing posts: https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java – theo Jan 07 '19 at 10:37
  • 1
    Many areas of the Java API have contracts which say that if two object match via `equals()`, then they should have the same hash code. If you _don't_ override `hashcode()` and enforce this, then the contract would break. – Tim Biegeleisen Jan 07 '19 at 10:38
  • Check this too :https://stackoverflow.com/questions/14608683/java-what-happens-if-hashcode-is-not-overriden – soorapadman Jan 07 '19 at 10:40

1 Answers1

1

If a.equals(b) is true, a.hashCode() == b.hashCode() must also be true. If it's not the case, adding a to a HashSet and then checking if set.contains(b) will return false even though the Set contains a, which is equal to b.

That's why the contract of hashCode() (in Object class) states that:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Eran
  • 387,369
  • 54
  • 702
  • 768