How to define a hash function for a list of objects?

I have a data structure containing a list of objects, for example:

class A {
  private List<Object> list;
}

How to correctly define a hash function for a list if each list item has the correct one hashCode()?

+3
source share
5 answers

If the actual implementation is Listfully consistent with the interface, the implementation hashCodeshould be sufficient:

Returns the hash code value for this list. The hash code of the list is determined as the result of the following calculation:

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

( List of documentation )

List equals . , hashCode

+6

hashCode , ( equals)?

( , java.util.List, , , , .)

+2

- . - , , - - , , . .

0

Java List (LinkedList, ArrayList) hashCode, AbstractList. :

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

, :

Arrays.hashCode(<cast list to array>);

- :

Arrays.hashCode((String []) myList.toArray());
0
source

Source: https://habr.com/ru/post/1750315/


All Articles