ArrayList 实现了Iterable,RandomAccess,Collection,List,Cloneable接口,其中RandomAccess,Cloneable 和Serializable是标记接口,表明实现随机访问,可克隆以及序列化
ArrayList里主要的几个变量
//默认初始化大小
private static final int DEFAULT_CAPACITY = 10;
//用于空实例的共享数组实例
private static final Object[] EMPTY_ELEMENTDATA = {};
//用于默认大小的空实例的共享空数组实例
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//储存ArrayList元素的缓冲区
transient Object[] elementData;
//ArrayList包含的元素个数
private int size;
//最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
protected transient int modCount = 0;
//最常用构造函数,构造一个初始化容量为10的数组
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//调用add方法来向list中添加元素
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 static int calculateCapacity(Object[] elementData, int minCapacity) {
//首次添加元素时,elementData中没东西,if表达式为true, minCapacity=1
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//此处直接返回DEFAULT_CAPACITY = 10
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
//modCount 继承自AbstractList 用于记录list结构修改的次数,即容量改变的次数,容量改变一次此处加一
modCount++;
//首次进入minCapacity为10,if 表达式为true
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
//首次oldCapacity = 0,minCapacity
int oldCapacity = elementData.length;
//oldCapacity >> 1,右位移运算符 num >> 1,相当于num除以2,所以此处首次仍然为0,newCapacity = minCapacity = 10;复制elementData中1-10个元素到elementData中
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);
}