1

By same result I mean, if two elements are equal(), am I obliged to make them have same hashCode() as well? What can go wrong if I don't do that?

First thing that came up to my mind is that 2 elements could be 'equal' in ArrayList, but not in HashSet. Is it bad practice to allow such behavior? And what problems could it make other than using contains() in them?

Ana Maria
  • 475
  • 2
  • 11
  • 2
    Does this answer your question? [What issues should be considered when overriding equals and hashCode in Java?](https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java) or [In Java, why must equals() and hashCode() be consistent?](https://stackoverflow.com/questions/1678205/in-java-why-must-equals-and-hashcode-be-consistent) – Ivar Jul 26 '20 at 11:46
  • 1
    Yes it does, thanks. Can't believe it didn't pop when I asked this. – Ana Maria Jul 26 '20 at 11:54

1 Answers1

1

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.

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#hashCode()

What could go wrong? Well, because hash code comparisons can be faster than full object comparisons, often the full comparison only happens if the hash code is equal. Thus, if your hashCode function is broken, your equality will be broken too.

  • 1
    May I suggest a more recent and precise [link](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#hashCode())? – Federico klez Culloca Jul 26 '20 at 11:49
  • 1
    I mean... it's not like anything's changed between Java 1.0 and today in this regard, but sure. –  Jul 26 '20 at 11:50