我有一个包含对象列表的数据结构,如下所示:
class A {
private List<Object> list;
}
假设列表的每个元素都有正确的 hashCode()
,如何为列表正确定义哈希函数?
最佳答案
如果实际的 List
实现完全符合接口(interface),提供的 hashCode
实现应该足够了:
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
接口(interface)需要符合要求的实现来提供 equals
基于列表的元素。因此,他们必须明确指定 hashCode
算法
关于java - 如何为对象列表正确定义哈希函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3054449/