Skip to content

Instantly share code, notes, and snippets.

@kymair
Created June 24, 2014 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kymair/cdb26b409fa7e385c820 to your computer and use it in GitHub Desktop.
Save kymair/cdb26b409fa7e385c820 to your computer and use it in GitHub Desktop.
Dive into Java Source
/* 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