java - 如何为对象列表正确定义哈希函数?

标签 java algorithm hash

我有一个包含对象列表的数据结构,如下所示:

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 documentation )

List 接口(interface)需要符合要求的实现来提供 equals基于列表的元素。因此,他们必须明确指定 hashCode 算法

关于java - 如何为对象列表正确定义哈希函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3054449/

相关文章:

algorithm - 无序集的哈希值?

javascript - 将哈希 HMAC SHA256 的 JS 加密代码移植到 PHP

java - 调用由 SWIG 生成的 JNI 的 UnsatisfiedLinkError?

java - java线程的状态到底意味着什么?

arrays - 如何在一次迭代中找到数组中的第二个最大元素?

algorithm - 微分方程 VS 算法复杂度

ruby - 不调用 `Hash#to_a` 将 Ruby 哈希转换为数组

java - Play Framework 清洁与清洁所有

java - 一个 jframe 中的多个 jpanel

arrays - 在给定父数组的情况下查找树的深度