/** 在元素序列 index 位置处插入 */ publicvoidadd(int index, E element){ if (index > size || index < 0) thrownew IndexOutOfBoundsException(outOfBoundsMsg(index));
public E remove(int index){ if (index >= size) thrownew IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++; // 返回被删除的元素值 E oldValue = (E) elementData[index];
int numMoved = size - index - 1; if (numMoved > 0) // 将 index + 1 及之后的元素向前移动一位,覆盖被删除值 System.arraycopy(elementData, index+1, elementData, index, numMoved); // 将最后一个元素置空,并将 size 值减 1 elementData[--size] = null; // clear to let GC do its work
return oldValue; }
E elementData(int index){ return (E) elementData[index]; }
/** 删除指定元素,若元素重复,则只删除下标最小的元素 */ publicbooleanremove(Object o){ if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { // 遍历数组,查找要删除元素的位置 for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }
/** 快速删除,不做边界检查,也不返回删除的元素值 */ privatevoidfastRemove(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 }