Created
June 24, 2014 01:27
-
-
Save kymair/cdb26b409fa7e385c820 to your computer and use it in GitHub Desktop.
Dive into Java Source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Bit Wtiddling Hacks http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 | |
java.util.ArrayDeque - find the nearest power of two */ | |
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 = new Object[initialCapacity]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment