Creating a hashCode() Method - Java

后端 未结 4 1102
暗喜
暗喜 2020-12-08 21:12

I\'m having some trouble writing a hashCode() method for a class I created. This class is meant to be used inside a TreeSet, and as such, it implements Comparab

4条回答
  •  执笔经年
    2020-12-08 22:06

    If your collection is small you can return constant from hashCode method. It use for quick finding. hashCodes is like the boxes, which keep elements. Rules are:

    1. Equal elements must be in same box (have same hashCode) - surely;
    2. Not equal elements can be either in same or in different boxes.

    Then you return constant, you obey these 2 rules, but it can significantly decrease perfomance on not small lists (because JVM will look for in all elements, and not in elements in the same box only). But return constant is the bad approach.

    PS: Sorry for my writing. English is not my native language.

    PPS: usualy you have to implement hashCode method in the same way as equals (use same elements)

提交回复
热议问题