今天在看 ArrayList 源码时,我发现了一个疑问。
ArrayList 有两个删除的方法分别是 remove(int index) 和 remove(Object o) 方法。
public E remove(int index) {
rangeCheck(index); // 检查下标是否合法
modCount++; // 修改次数加一
E oldValue = elementData(index); // 获取 index 位置旧值
int numMoved = size - index - 1; // 需要移动的元素个数
if (numMoved > 0) // 大于0,index 索引处后面的元素向前移动一位
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// size-- 将元素尾置为 null, 返回旧值
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public boolean remove(Object o) {
if (o == null) { // 如果待移除的元素是 null ,那么遍历找到元素为 null的元素,调用 fastRemove
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {// 不为 null 则找到元素与待移除元素相同的元素,调用 fastRemove
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
看完两个方法后,我发现第二个根据元素移除的方法中调用了一个私有方法fastRemove方法,这个方法的源码如下:
private void fastRemove(int index) {
modCount++; // 修改次数加一
int numMoved = size - index - 1; // 需移动元素的个数
if (numMoved > 0) // 移动
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// size--
elementData[--size] = null; // clear to let GC do its work
}
看到这个方法是不是和根据索引移除元素的方法非常相似,他们的区别仅仅只是多了一个索引的合法性检查和返回旧元素值,我很疑问为什么 remove(int index) 方法不直接调用 fastRemove方法呢?希望知道的大佬帮忙解决这个问题,感谢!!!