直接使用for循环删除ArrayList的元素有什么影响?

11 篇文章 0 订阅

许久都未写技术文章了,实在是有些怠惰了,自觉惭愧啊。


在Java中使用for循环直接删除ArrayList中的特定元素是错的,不同的for循环方式会发生不同的错误,比如泛型的for会抛出ConcurrentModificationException,而普通的for想要删除集合中重复且连续的元素则只能删除第一个。

错误原因

我们打开JDK的ArrayList源码,看一下ArrayList中的remove方法是如何实现的(注意ArrayList中的remove有两个同名方法,只是入参不同,这里我们看的是入参为Object的remove方法):

/** 此处使用的是jdk11.0.7的代码 **/ 
/**
 * Removes the first occurrence of the specified element from this list,
 * if it is present.  If the list does not contain the element, it is
 * unchanged.  More formally, removes the element with the lowest index
 * {@code i} such that
 * {@code Objects.equals(o, get(i))}
 * (if such an element exists).  Returns {@code true} if this list
 * contained the specified element (or equivalently, if this list
 * changed as a result of the call).
 *
 * @param o element to be removed from this list, if present
 * @return {@code true} if this list contained the specified element
 */
public boolean remove(Object o) {
    final Object[] es = elementData;
    final int size = this.size;
    int i = 0;
    found: {
        if (o == null) {
            for (; i < size; i++)
                if (es[i] == null)
                    break found;
        } else {
            for (; i < size; i++)
                if (o.equals(es[i]))
                    break found;
        }
        return false;
    }
    fastRemove(es, i);
    return true;
}

/**
 * Private remove method that skips bounds checking and does not
 * return the value removed.
 */
private void fastRemove(Object[] es, int i) {
    modCount++;
    final int newSize;
    if ((newSize = size - 1) > i)
        System.arraycopy(es, i + 1, es, i, newSize - i);
    es[size = newSize] = null;
}

可以看到,一般情况下,程序的执行路径会走到else路径下并最终调用fastRemove方法,然后执行System.arraycopy方法,从而导致删除元素时涉及到数组元素的移动。

考虑下面这样一个ArrayList集合:

List<String> list = new ArrayList(Arrays.asList("a", "b", "b", "c", "d"));

针对普通for循环的错误写法可以想到,在遍历第一个字符串b时因为符合删除条件,所以将该元素从数组中删除,然后将后一个元素移动(也就是第二个字符串b)至当前位置,导致下一次循环遍历时后一个字符串b并没有遍历到,所以不可以以这样的方式删除。但是针对这种情况可以用倒序删除的方式来避免。

最优的解决方案:使用iterator。

List<String> list = new ArrayList(Arrays.asList("a", "b", "b", "c", "d"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    if (element.equals("b")) {
        iterator.remove();
    }
}

把这个问题扩展一下,考虑下面的代码可能会出现什么问题?

ArrayList<String> array = new ArrayList<String>();
array.add(1, "hello world");

对,就是超出界限的IndexOutOfBoundsException错误啦~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值