繁体   English   中英

在 HashMap 的节点中存储 hash 的目的是什么?

[英]What is the purpose of storing hash in Node of HashMap?

static class Node implements Map.Entry {
      final int hash;
      final K key;
      V value;
      Node next;

}

在java中HashMap的内部实现中,Node存储了hash。

为什么使用它? 我认为没有必要这样做。

我相信主要原因是提高性能。 对于某些对象,调用equals()可能会很昂贵。 短路评估的帮助下,如果 hash 不匹配,jvm 不必调用equals()

这就是getNode的实现方式(在遍历存储桶以搜索节点时调用。

     if (first.hash == hash && 
         ((k = first.key) == key || (key != null && key.equals(k))))

//( Same HashCode AND ((Same Object reference of the Key) OR (equal method says True in Key Object) )

编辑:正如@moreON 所述,重新散列还需要 hash

对于典型的 hash 表实现,在重新散列 hash 表时将再次需要散列(也就是说,当它的容量通常因为太满而发生变化时)。 因为密钥的 hash 无法更改并且可能是一项昂贵的操作,所以存储它以减少这种不常见但昂贵的操作所花费的时间是明智的。

Other hash map implementations that use open addressing will need the hash more often than this, so for those it is even more important that the hash for existing entries is very fast to find. 我不确定 java hash map 使用什么碰撞分辨率。

编辑:Andy K 在他的回答中提出的观点也不是很好(我完全错过了)-添加项目时,需要对键进行严格的相等比较-由于尺寸小得多,任何冲突解决方案都会发生多个哈希冲突hash map 比 hash 函数的一组可能结果。 使用预先计算的 hash 可以在此处进行快速的不等式测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM