The quoted code snippet from the JDK 7 java.util.ArrayList class confuses me. I can't for the life of me understand how can it possibly result in overflow. The areas which I'm confused in are marked with <--- what do they mean by this?. Can someone please help me out in understanding the circumstances under which this logic might overflow? TIA.
public void ensureCapacity(int minCapacity) {
if (minCapacity > 0)
ensureCapacityInternal(minCapacity);
}
private void ensureCapacityInternal(int minCapacity) {
modCount++;
// overflow-conscious code <--- what do they mean by this?
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code <--- what do they mean by this?
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow <--- what do they mean by this?
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
EDIT: My main concern is: how can hugeCapacity ever receive a negative size?
new OutOfMemoryError()inhugeCapacity()method is the one which has got me confused.