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?
The
OutOfMemoryError()(inArrayList) is thrown for 2 conditions:minCapacityis less that zero. That means that a memory array allocation cannot be created, i.e.elementDataarray size cannot be less that zero.grow()) to allocate more object in the array.Hence why
hugeCapacity()ensures that memory is allocated safely.grow()andhugeCapacity()is only used withinensureCapacityInternal(), so one can say that theminCapacity < 0is unecessary. I believe it’s a safety check put in place, just to render the growing of array safe. Any discrepency, rather throw an error.