ArrayList
的底层操作机制源码分析
ArrayList
中维护一个Object类型的数组elementData
transient Object[] elementData;
//transient表示瞬间 短暂的,表示该属性不会被序列化- 当创建
ArrayList
对象时,如果使用的是无参构造器,则初始elementData容量为0,第一次添加,则扩容elementData
为10,如需再次扩容,则扩容elementData
为1.5倍 - 如果使用的是指定大小的构造器,则初始
elementData
容量为指定大小,如需再次扩容,则直接扩容elementData
为1.5倍
public class ArrayListSource_ {public static void main(String[] args) {ArrayList list = new ArrayList(8);// ArrayList list = new ArrayList();for (int i = 1; i <= 10; i++) {list.add(i);}for (int i = 11; i <= 15; i++) {list.add(i);}list.add(200);list.add(200);list.add(null);}
}
public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}
public boolean add(E e) {ensureCapacityInternal(size + 1); // Increments modCount!!elementData[size++] = e;return true;}
private static int calculateCapacity(Object[] elementData, int minCapacity) {if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {return Math.max(DEFAULT_CAPACITY, minCapacity);}return minCapacity;}
private void ensureCapacityInternal(int minCapacity) {ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));}
private void grow(int minCapacity) {// overflow-conscious codeint 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);}
具体的执行流程