1. ArrayList的构造方法,源码如下:
1
/**
2
* Shared empty array instance used for default sized empty instances. We
3
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
4
* first element is added.
5
*/
6
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
7
8
/**
9
* The array buffer into which the elements of the ArrayList are stored.
10
* The capacity of the ArrayList is the length of this array buffer. Any
11
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
12
* will be expanded to DEFAULT_CAPACITY when the first element is added.
13
*/
14
transient Object[] elementData; // non-private to simplify nested class access
1
/**
2
* Constructs an empty list with an initial capacity of ten.
3
*/
4
public ArrayList() {
5
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
6
}
2. ArrayList类add方法的详解
1
public boolean add(E e) {
2
ensureCapacityInternal(size + 1); // Increments modCount!!
3
elementData[size++] = e;
4
return true;
5
}
3. 调用的是ensureCapacityInternal方法,我们就看一看这个方法的源码
1
private void ensureCapacityInternal(int minCapacity) {
2
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//如果是第一次添加元素,则执行下面方法
3
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
4
}
5
6
ensureExplicitCapacity(minCapacity);
7
}
4. ensureExplicitCapacity方法的解析
1
private void ensureExplicitCapacity(int minCapacity) {
2
modCount++; //记录修改的次数
3
4
// overflow-conscious code
5
if (minCapacity - elementData.length > 0)
6
grow(minCapacity);//如果minCapacity比原数组的容量大,则进行扩容操作
7
}
5. grow方法如下所示:
1
private void grow(int minCapacity) {
2
// overflow-conscious code
3
int oldCapacity = elementData.length;
4
int newCapacity = oldCapacity + (oldCapacity >> 1);//数组扩容1.5倍
5
if (newCapacity - minCapacity < 0)
6
newCapacity = minCapacity;
7
if (newCapacity - MAX_ARRAY_SIZE > 0)
8
newCapacity = hugeCapacity(minCapacity);
9
// minCapacity is usually close to size, so this is a win:
10
elementData = Arrays.copyOf(elementData, newCapacity);//扩容核心方法,将elementData复制到新的数组中并扩容
11
}
6. 按照index的位置添加元素
1
public void add(int index, E element) {
2
rangeCheckForAdd(index);
3
4
ensureCapacityInternal(size + 1); // Increments modCount!!//先扩容
5
System.arraycopy(elementData, index, elementData, index + 1,
6
size - index);//复制数组后半部分
7
elementData[index] = element;//插入元素
8
size++; //增加计数器
9
}