上一节介绍了ArrayList 的创建 和add流程,不清楚的可以看一下https://blog.csdn.net/ruanjiandu/article/details/111093162
1 本节介绍remove 的流程
1.1 remove 具体位置的元素
ArrayList<String> listq = new ArrayList<>();
listq.add("1");
listq.add("2");
listq.add("3");
listq.add("4");
listq.remove(2);//删除 index 2的元素
老规矩,看源码解释
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
public E remove(int index) {//删除指定位置的元素
if (index >= size)//判断删除位置是否超过老arraylist的长度
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++;//操作次数。可忽略
E oldValue = (E) elementData[index];//取出 即将被删除的对象
int numMoved = size - index - 1;//计算要复制源数组到目的数组的个数
if (numMoved > 0)//要复制的个数大于0
//第一个elementData 代表源数组,index+1 从源数组开始复制的位置
//第二个elementData 代表目的数组,index 开始要被复制的起始位置
//numMoved 要复制的数量
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; //最后一个数组元素置为空,可被GC回收
return oldValue;//返回被删除的对象
}
}
2 remove 某个元素
ArrayList<String> listq = new ArrayList<>();
listq.add("1");
listq.add("2");
listq.add("3");
listq.add("4");
listq.remove(“3”);//删除 元素是“3”的
//删除具体元素
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 remove method that skips bounds checking and does not
* return the value removed.
*/
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
}
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}