Why we should Override hashcode() when overriding equals() method? [duplicate]

StackOverflow https://stackoverflow.com/questions/20883469

  •  23-09-2022
  •  | 
  •  

Вопрос

Why we should always override hashCode() method whenever we override equals() method? As per my understanding they both seem to fulfill different purpose. hashCode() method is used in hashtables to determine the equality of keys. However equals() method is used to determine the equality of two objects.

Это было полезно?

Решение

If two objects are equal according to the equals method, their hashcodes must be equal as well. Otherwise, lookup in the hash table would fail.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top