ArrayList的Remove操作有两种,一是指定下标的删除,二是指定对象的删除。指定对象的删除是根据对象的equals方法,找到其在数组中的第一个位置,并根据下标进行删除,需要注意的是每次调用对象remove是只会remove一个。
下面是ArrayList的remove源码:
/**
移除list中指定位置的元素
* Removes the element at the specified position in this list.
所有后续元素左移 下标减1
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*参数是要移除元素的下标
* @param index the index of the element to be removed
返回值是被移除的元素
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
//下标越界检查
rangeCheck(index);
//修改次数统计
modCount++;
//获取这个下标上的值
E oldValue = elementData(index);
//计算出需要移动的元素个数 (因为需要将后续元素左移一位 此处计算出来的是后续元素的位数)
int numMoved = size - index - 1;
//如果这个值大于0 说明后续有元素需要左移 是0说明被移除的对象就是最后一位元素
if (numMoved > 0)
//索引index只有的所有元素左移一位 覆盖掉index位置上的元素
System.arraycopy(elementData, index+1, elementData, index,numMoved);
// 将最后一个元素赋值为null 这样就可以被gc回收了
elementData[--size] = null; // clear to let GC do its work
//返回index位置上的元素
return oldValue;
}
//移除特定元素
public boolean remove(Object o) {
//如果元素是null 遍历数组移除第一个null
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
//遍历找到第一个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; // clear to let GC do its work
}