I was reading Java\'s ArrayList source code and noticed some comparisons in if-statements.
In Java 7, the method grow(int) uses
if (newC
Looking at the code:
int newCapacity = oldCapacity + (oldCapacity >> 1);
If oldCapacity is quite large, this will overflow, and newCapacity will be a negative number. A comparison like newCapacity < oldCapacity will incorrectly evaluate true and the ArrayList will fail to grow.
Instead, the code as written (newCapacity - minCapacity < 0 returns false) will allow the negative value of newCapacity to be further evaluated in the next line, resulting in recalculating newCapacity by invoking hugeCapacity (newCapacity = hugeCapacity(minCapacity);) to allow for the ArrayList to grow up to MAX_ARRAY_SIZE.
This is what the // overflow-conscious code comment is trying to communicate, though rather obliquely.
So, bottom line, the new comparison protects against allocating an ArrayList larger than the predefined MAX_ARRAY_SIZE while allowing it to grow right up to that limit if needed.