今天在看 ArrayList 源码时,我发现了一个疑问。
ArrayList 有两个删除的方法分别是 remove(int index) 和 remove(Object o) 方法。
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[--size] = null;
return oldValue;
}
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;
}
看完两个方法后,我发现第二个根据元素移除的方法中调用了一个私有方法fastRemove方法,这个方法的源码如下:
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;
}
看到这个方法是不是和根据索引移除元素的方法非常相似,他们的区别仅仅只是多了一个索引的合法性检查和返回旧元素值,我很疑问为什么 remove(int index) 方法不直接调用 fastRemove方法呢?希望知道的大佬帮忙解决这个问题,感谢!!!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)