Skip to content

Instantly share code, notes, and snippets.

@lichenbo
Created July 13, 2013 09:30
Show Gist options
  • Save lichenbo/5990159 to your computer and use it in GitHub Desktop.
Save lichenbo/5990159 to your computer and use it in GitHub Desktop.
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];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment