elementData是arraylist的容器,所以arraylist是基于数组的操作。
transient Object[] elementData;
add
添加一个元素前,先检查数组容量,如果数组为空,先初始化。
发现容量不够时,需要对数组扩容。初始容量是10.
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
记录修改结构的操作次数modCount
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity); //数组容量一般扩大50%,容量大于Integer.MAX_VALUE - 8时,扩容为Integer.MAX_VALUE
}
get
检查索引有没有越界,没有就返回索引处的值。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
remove
只移除第一个为o的元素。
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;
}