Why hashmap lookup is O(1) i.e. constant time?

前端 未结 3 2125
借酒劲吻你
借酒劲吻你 2020-11-30 01:12

If we look from Java perspective then we can say that hashmap lookup takes constant time. But what about internal implementation? It still would have to search through parti

3条回答
  •  醉话见心
    2020-11-30 01:56

    The key is in this statement in the docs:

    If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table.

    and

    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.

    http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

    The internal bucket structure will actually be rebuilt if the load factor is exceeded, allowing for the amortized cost of get and put to be O(1).

    Note that if the internal structure is rebuilt, that introduces a performance penalty that is likely to be O(N), so quite a few get and put may be required before the amortized cost approaches O(1) again. For that reason, plan the initial capacity and load factor appropriately, so that you neither waste space, nor trigger avoidable rebuilding of the internal structure.

提交回复
热议问题