您好,登錄后才能下訂單哦!
/**
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
@serial
*/
private int size;
//最大數(shù)組大小
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//默認(rèn)實例為一個空數(shù)組
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//添加元素
public boolean add(E e) {
//確定容量
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//超過擴(kuò)容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//擴(kuò)容方式 舊容量+舊容量右移一位
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);
}
//循環(huán)清除
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
//刪除 --很巧妙的刪除
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
//獲得需要移動的位數(shù)
int numMoved = size - index - 1;
if (numMoved > 0)
//進(jìn)行復(fù)制,最后一位會保留下來
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//數(shù)組大小減少一位,最后一位賦值為空
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。