1.返回删除元素的删除方法
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中(index+1,size-1)复制到(index,size-1)elementData[--size] = null; // size-1,最后一个元素置为nullreturn oldValue;
}
下标检查,如果大于数组的size,抛出异常
private void rangeCheck(int index) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
2.返回一个boolean值的删除方法
2.1传进来null,删除第一个值为null的值(注意此时加入了两个null值)
此时执行了一句list.remove(null);只删除了在物理位置上比较靠前的null,第二次删除才会删除第二个null
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;
}
此方法执行的就是上面"返回删除元素"方法中的内容
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;
}
3.从这个列表中删除所有未包含在指定集合中的元素
public boolean retainAll(Collection<?> c) {Objects.requireNonNull(c); // 检查,如果此对象为空,抛出空指针异常return batchRemove(c, true);
}
private boolean batchRemove(Collection<?> c, boolean complement) {final Object[] elementData = this.elementData;int r = 0, w = 0;boolean modified = false;try {for (; r < size; r++)//如果传入的集合c,包含当前所遍历的数组的元素,重新整理一下list中的元素if (c.contains(elementData[r]) == complement)elementData[w++] = elementData[r];} finally {// 抛出异常后的处理(下面为JDK中的描述)// Preserve behavioral compatibility with AbstractCollection,// even if c.contains() throws.if (r != size) {System.arraycopy(elementData, r,elementData, w,size - r);w += size - r;}if (w != size) {// clear to let GC do its workfor (int i = w; i < size; i++)elementData[i] = null;modCount += size - w;size = w;modified = true;}}return modified;
}