0

Maybe this question seems ridiculous for you, but I clearly do not understand (I am junior Java) why should we override equals() and hashCode() often together?

Indeed, I can override equals() for some class to make a specific comparing, but why should I override hashCode() too? Thank you very much!

tquadrat
  • 3,033
  • 1
  • 16
  • 29
Mikhail
  • 195
  • 2
  • 12
  • there are tons of sources about this, no doubt your textbook also provides information about this: https://www.geeksforgeeks.org/override-equalsobject-hashcode-method/ – Stultuske May 20 '20 at 05:54
  • https://stackoverflow.com/a/2265637/10476860 Even on SO there are some sources about this. – Embid123 May 20 '20 at 05:55

1 Answers1

3

Several collections like for example HashSet rely on the fact that equals and hashCode are consistent. That means that hashCode must give the same value when the objects are equal in the sense of equals.

Henry
  • 42,982
  • 7
  • 68
  • 84