ArrayList 特有的方法(一般也是用的其父類List的方法):
ensureCapacity(int minCapacity) //初始化容量
trimToSize() //清除剩余容量
筆試題目:
使用ArrayList無參的構(gòu)造函數(shù)創(chuàng)建一個 對象時, 默認(rèn)的容量是多少? 如果長度不夠使用時又自增增長多少?
ArrayList底層是維護了一個Object數(shù)組實現(xiàn) 的,使用無參構(gòu)造函數(shù)時,Object數(shù)組默認(rèn)的容量是10,當(dāng)長度不夠時,自動增長0.5倍。
原理剖析:
私有變量:
private transient Object[] elementData;//維護的Object數(shù)組
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//ArrayList最大容量
構(gòu)造方法:
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0) //容量小于0拋出異常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];//創(chuàng)建對應(yīng)容量數(shù)組
}
public ArrayList() {
this(10); //默認(rèn)容量10
}
添加數(shù)據(jù)方法:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/*如果最小需求容量 - 當(dāng)前空間容量 > 0 代表"當(dāng)前容量不夠"*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//a >> n =a / 2^n
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);
}
/*newCapacity = oldCapacity + oldCapacity/2
如果newCapacity還是小于oldCapacity,那么新容量就用oldCapacity
如果newCapacity大于了最大容量,那么就會進行大容量處理*/
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}