Why should I override hashCode() when I override equals() method?

后端 未结 5 2110
夕颜
夕颜 2020-11-27 05:22

Ok, I have heard from many places and sources that whenever I override the equals() method, I need to override the hashCode() method as well. But consider the following piec

5条回答
  •  旧时难觅i
    2020-11-27 06:08

    It is primarily important when searching for an object using its hashCode() value in a collection (i.e. HashMap, HashSet, etc.). Each object returns a different hashCode() value therefore you must override this method to consistently generate a hashCode value based on the state of the object to help the Collections algorithm locate values on the hash table.

提交回复
热议问题