HashMap中的哈希冲突 [英] Hash Collisions in HashMap

查看:48
本文介绍了HashMap中的哈希冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解Java的 HashMap

1. 密钥对象 hashCode()产生与已经产生的值相同的 hash值(即使哈希存储桶尚未满)

1.hashCode() for Key Object produces same hash value as already produced one ( even if hash bucket is not full yet )

2.哈希存储桶已满,因此必须在现有索引处添加新的 Entry .

2.Hash Bucket is already full so new Entry has to go at existing index.

在Java的 HashMap 情况下,情况#2 确实很少见,原因是允许的条目数量如此之多并自动调整大小(请参见

In case of Java's HashMap, situation#2 would really be rare due to so large number of allowed entries and automatic resizing ( See My other question )

我的理解正确吗?

但是出于理论知识的考虑,程序员或JVM是否可以做任何事情还是可以做任何事情来避免方案#2?或

But for the sake of theoretical knowledge, do programmers or JVM do anything or can do anything to avoid scenario # 2? OR

是否允许 hash-bucket 尽可能大,然后继续调整唯一策略的大小?(如 HashMap 一样进行).

Is allowing hash-bucket to be of largest possible size and then continous re sizing the only strategy? ( As is being done in case of HashMap ).

我想,作为一名程序员,我应该只专注于编写良好的 hasCode(),而不用担心方案2(因为API已经解决了该问题).

I guess, as a programmer , I should be focused in writing a good hasCode() only and not worry about scenario#2 ( since that is already taken care of by API ).

推荐答案

我认为#2是#1的特例,它确实是一样的,因为当HashMap决定将新元素放在何处时,它决定不是因为一切否则,如果已满,但是因为hashCode与地图中已经存在的元素相同.

I think #2 is a special case of #1, it's really the same, as when HashMap decides where to put the new element, it decides not because everything else if full, but because the hashCode is the same as for an element that's already in the map.

我同意,您应该专注于 hasCode(),请参见:

I agree, you should focus on the hasCode(), see: Creating a hashCode() Method - Java

这篇关于HashMap中的哈希冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆