ArrayList中remove(int index)方法中为什么不使用fastRemove方法?

今天在看 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方法呢?希望知道的大佬帮忙解决这个问题,感谢!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值