初始
ArrayList是通过数组实现容量大小动态变化。允许null的存在。同时也实现了RandomAccess,Cloneable,Serializable接口(表示ArrayList支持快速访问,复制,序列化)
结构
成员变量
private int size ; //数组大小
transient Object[] elementData; //存储元素的数组
方法
- 初始化
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; public ArrayList(){ this.elementData = {};//指向的是一个空对象//初始化的时候不会赋值容量大小,只会构建一个空的数组 }
- add
public boolean add(E e){
ensureCapacityInternal(size+1);
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity){
if (elementData == {}){
minCapacity = Math.max(10, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity){
modCount++;
if (minCapacity - elementData.length > 0){
grow(minCapacity);
}
}
private void grow(int minCapacity){
int oldCapacity = elementData.length;
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);
}
删除
public boolean remove(Object o) {
//说明了ArrayList中是可以存储null值
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;
}