初探ArrayList之删除

1.返回删除元素的删除方法
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中(index+1,size-1)复制到(index,size-1)
    elementData[--size] = null; // size-1,最后一个元素置为null
    
    return oldValue;
}

下标检查,如果大于数组的size,抛出异常

private void rangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
2.返回一个boolean值的删除方法

2.1传进来null,删除第一个值为null的值(注意此时加入了两个null值)

clipboard.png

此时执行了一句list.remove(null);只删除了在物理位置上比较靠前的null,第二次删除才会删除第二个null

clipboard.png

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 void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
    System.arraycopy(elementData, index+1, elementData, index,
                     numMoved);
    elementData[--size] = null;
}
3.从这个列表中删除所有未包含在指定集合中的元素
public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c); // 检查,如果此对象为空,抛出空指针异常
    return batchRemove(c, true);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            //如果传入的集合c,包含当前所遍历的数组的元素,重新整理一下list中的元素
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        // 抛出异常后的处理(下面为JDK中的描述)
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        if (r != size) {
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            // clear to let GC do its work
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值