Does a HashMap collision cause a resize?

非 Y 不嫁゛ 提交于 2019-12-01 06:02:40

问题


When there is a collision during a put in a HashMap is the map resized or is the entry added to a list in that particular bucket?


回答1:


When you say 'collision', do you mean the same hashcode? The hashcode is used to determine what bucket in a HashMap is to be used, and the bucket is made up of a linked list of all the entries with the same hashcode. The entries are then compared for equality (using .equals()) before being returned or booted (get/put).

Note that this is the HashMap specifically (since that's the one you asked about), and with other implementations, YMMV.




回答2:


Either could happen - it depends on the fill ratio of the HashMap.

Usually however, it will be added to the list for that bucket - the HashMap class is designed so that resizes are comparatively rare (because they are more expensive).




回答3:


The documentation of java.util.HashMap explains exactly when the map is resized:

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor.

The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.

The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.

When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

The default initial capacity is 16, the default load factor is 0.75. You can supply other values in the map's constructor.




回答4:


Resising is done when the load factor is reached.

When there is a collision during a put in a HashMap the entry is added to a list in that particular "bucket". If the load factor is reached, the Hashmap is resized.



来源:https://stackoverflow.com/questions/2239345/does-a-hashmap-collision-cause-a-resize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!