Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a data structure containing a list of objects, like this:

class A {
  private List<Object> list;
}

How to properly define a hash function for the list, assuming each element of the list has a correct hashCode()?

like image 849
ansgri Avatar asked Jun 16 '10 14:06

ansgri


2 Answers

If the actual List implementation is fully conformant to the interface, the provided hashCode implementation should be sufficient:

Returns the hash code value for this list. The hash code of a list is defined to be 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 documentation)

The List interface requires conforming implementations to provide equals based on the elements of the list. Thus, they had to specify the hashCode algorithm explicitely

like image 171
Dirk Avatar answered Oct 12 '22 14:10

Dirk


Why do you want to define hashCode for your list, when it already has it implemented (along with equals)?

(Provided it is java.util.List of course - however if not, the link above shows you the exact implementation you can use for your own list type.)

like image 44
Péter Török Avatar answered Oct 12 '22 14:10

Péter Török