JDK 7 java.util.ArrayList
類中的引用代碼段令我感到困惑。我不能爲我的生活理解它怎麼可能導致溢出。我很困惑的區域用<--- what do they mean by this?
標記。有人能幫助我理解這種邏輯可能溢出的情況嗎? TIA。在Java中調整ArrayList的大小時,無法理解溢出的可能性
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;
}
編輯:我主要關心的是:hugeCapacity如何能夠獲得負尺寸?
如果您對Java代碼中的註釋感興趣,它不是「堆棧溢出」溢出。它關於內部陣列的管理容量。 – 2011-12-19 06:30:42
@jowierun:你說得對,堆棧溢出不是我關心的地方。我很確定這些評論說的是數據類型溢出/容量溢出。 'hugeCapacity()'方法中的新'OutOfMemoryError()'會讓我感到困惑。 – sasuke 2011-12-19 06:35:50