數組怎麼實現動態分配長度?數組的長度為什麼不固定?求大神講解
沒有動態,最終還是數組復制,小數組換大數組
//這是數據擴充的核心代碼,最終就是arrays.copyof
private void grow(int minCapacity) {
// overflow-conscious code
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);
}