一 属性
//初始容量private static final int DEFAULT_CAPACITY = 10;//指定arrayList容量为0的时候返回这个数组private static final Object[] EMPTY_ELEMENTDATA = {};//构造无参的对象的时候,返回这个private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};//存放元素,第一次添加元素的时候扩容到 初始容量10transient Object[] elementData; // non-private to simplify nested class accessprivate int size;
二 重要方法
- Arrays.copyOf(elementData, size)
- 底层的数组拷贝
- ensureCapacity(int minCapacity)
- 扩容方法(每次扩容原来容量的1.5倍)
- System.arraycopy(elementData, 0, a, 0, size);
- 底层数组的拷贝 本地方法
trimToSize
- 将数组缩容为实际的容量,数组每次扩容会增加 newCapacity = oldCapacity + (oldCapacity >> 1)
-
三 添加
public boolean add(E e) {ensureCapacityInternal(size + 1); // Increments modCount!!elementData[size++] = e;return true;}
四 获取
public E get(int index) {rangeCheck(index);return elementData(index);}
五 删除
public E remove(int index) {rangeCheck(index);modCount++;E oldValue = elementData(index);int numMoved = size - index - 1;if (numMoved > 0)System.arraycopy(elementData, index+1, elementData, index,numMoved);//最后一位gc回收elementData[--size] = null; // clear to let GC do its workreturn oldValue;}
六 扩容
```java private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); }
private void ensureExplicitCapacity(int minCapacity) { modCount++;
// overflow-conscious code 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 codeint oldCapacity = elementData.length;//扩容大小为原来长度的1.5倍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) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}
```
