Does a HashMap collision cause a resize?

前端 未结 4 1936
别那么骄傲
别那么骄傲 2021-01-14 15:03

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?

相关标签:
4条回答
  • 2021-01-14 15:23

    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.

    0 讨论(0)
  • 2021-01-14 15:27

    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.

    0 讨论(0)
  • 2021-01-14 15:28

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

    0 讨论(0)
  • 2021-01-14 15:36

    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.

    0 讨论(0)
提交回复
热议问题