ArrayList
1. ArrayList的生命周期
import java.util.ArrayList;
public class MainClass {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("SeekWind");
arrayList.remove("SeekWind");
}
}
1. 生成一个空数组
// 生成一个空的数组
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
其长度的初始化为懒模式。如果我们不向其添加元素,则长度为0。
2. add时扩容
JDK默认长度下限为10。
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 扩容50%
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);
}
3. remove删除元素
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
// 遍历集合以查找null值删除
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;
}
其中调用了fastRemove方法
private void fastRemove(int index) {
modCount++;
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
}