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()
?
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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With