Why is the initialCapacity of Hashtable 11 while the DEFAULT_INITIAL_CAPACITY in HashMap is 16 and requires a power of 2?

后端 未结 4 1005
耶瑟儿~
耶瑟儿~ 2021-01-30 13:42

Comparing the HashMap and Hashtable source code in JDK 1.6, I saw the below code inside HashMap:

/**
 * The default initial capacity -          


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 14:27

    This could help:

    http://www.concentric.net/~Ttwang/tech/primehash.htm

    Basicly, if I remember correctly, when you have a hash table with a size that is power of 2, it's easy to get a hash function based on the less relevant bits of the key.

    Using a prime number (as in 11) as the size of the table, makes collision on the table rows less likely, so inserting is "cheaper".

提交回复
热议问题