我看的Java 1.6的java.util.ArrayDeque中(隊列實現)的源極和偶然在allocateElements()的執行情況,其大小應該根據給定的數背襯陣列元素:ArrayDeque.allocateElements(按位操作)
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2^30 elements
}
elements = (E[]) new Object[initialCapacity];
}
ORC initialCapacity與自己的rshifted是什麼目的?
雅得愛Bloch和Lea的註釋。 :-) – trashgod 2011-04-03 08:32:32
感謝詳細的解答!可恥的是我不知道如何找到最近的2的功率爲位操作! – 2011-04-03 09:11:49
不客氣。這是我最喜歡的一個[*位操作黑客*](https://graphics.stanford.edu/~seander/bithacks.html)。 – trashgod 2016-06-27 09:18:21