ArrayList原理与源码解析

ArrayList 原理与源码解析

1、原理

2、源码解析

2.1、构造方法

1
2
3
4
5
6
7
8
9
10
11
12
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//创建数组,根据传入大小
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//创建空数组
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}

2.2、add 方法

1
2
3
4
5
6
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
//往数组中插入元素
elementData[size++] = e;
return true;
}

2.3、remove 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public boolean remove(Object o) {
if (o == null) {
//查找到要删除的值,再删除
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
//查找到要删除的值,再删除
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
//按照索引删除,底层与按索引删除方法相同
fastRemove(index);
return true;
}
}
return false;
}