Best implementation for hashCode method for a collection

后端 未结 20 3575
难免孤独
难免孤独 2020-11-22 01:39

How do we decide on the best implementation of hashCode() method for a collection (assuming that equals method has been overridden correctly) ?

20条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 02:35

    If I understand your question correctly, you have a custom collection class (i.e. a new class that extends from the Collection interface) and you want to implement the hashCode() method.

    If your collection class extends AbstractList, then you don't have to worry about it, there is already an implementation of equals() and hashCode() that works by iterating through all the objects and adding their hashCodes() together.

       public int hashCode() {
          int hashCode = 1;
          Iterator i = iterator();
          while (i.hasNext()) {
            Object obj = i.next();
            hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
          }
      return hashCode;
       }
    

    Now if what you want is the best way to calculate the hash code for a specific class, I normally use the ^ (bitwise exclusive or) operator to process all fields that I use in the equals method:

    public int hashCode(){
       return intMember ^ (stringField != null ? stringField.hashCode() : 0);
    }
    

提交回复
热议问题