significance of “power of 2” in java.util.HashMap implementation [duplicate]

廉价感情. 提交于 2019-12-13 11:42:36

问题


Possible Duplicate:
Java HashMap Default Initial Capacity

I was reading the implementation of HashMap in java.util.HashMap. The initial capacity,maximum capacity etc., are powers of two.

Parts of declaration copied from java.util.HashMap

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 16;


 /**
 * The maximum capacity, used if a higher value is implicitly specified
 * by either of the constructors with arguments.
 * MUST be a power of two <= 1<<30.
 */
static final int MAXIMUM_CAPACITY = 1 << 30;


/**
 * The table, resized as necessary. Length MUST Always be a power of two.
 */
transient Entry[] table;

The comments suggest the sizes MUST be a power of two. Why is power of two given so much importance ?


回答1:


Using powers of two simplifies the implementation and improves its performance.

E.g. to find a bucket from a hash code it can use hash & (SIZE -1) instead of abs(hash) % SIZE




回答2:


Theoretically speaking, we can amortize the cost of expanding the list only if the operation becomes negligible as the number of elements in the map increases. Doubling the size every time the load factor is reached is one way of ensuring the expansion and reloading of entries is amortized.

The reason why it is specifically a power of two initially is so that when we hash an element, the resulting integer (32-bits) can be truncated to the first k-bits, where k is the log (N) where N is the current capacity.



来源:https://stackoverflow.com/questions/10632506/significance-of-power-of-2-in-java-util-hashmap-implementation

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