直接使用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错误啦~

Java中,直接在`for`循环删除集合元素可能导致`ConcurrentModificationException`异常,这是因为迭代器的快速失败行为。为了避免这种情况,推荐使用迭代器(Iterator)的`remove`方法来安全地删除元素。下面是使用迭代器删除集合元素的正确方式: ```java import java.util.ArrayList; import java.util.Iterator; public class RemoveElement { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()) { Integer element = iterator.next(); if (element == 3) { // 假设我们要删除元素3 iterator.remove(); // 使用迭代器的remove方法删除元素 } } System.out.println(list); // 输出修改后的集合 } } ``` 在这个例子中,我们在遍历`ArrayList`时,使用`iterator()`方法获得一个迭代器,然后在`while`循环中检查每个元素。如果元素符合条件(比如等于3),我们就调用迭代器的`remove()`方法来删除它。这样就不抛出`ConcurrentModificationException`异常。 使用`for-each`循环删除元素通常不是安全的做法,因为它没有提供直接调用`remove`的方法。但是,如果确实需要在`for-each`循环删除元素,可以在循环体内使用条件判断来调用迭代器的`remove`方法。例如: ```java for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext(); ) { Integer element = iterator.next(); if (element == 3) { // 如果元素等于3,使用迭代器的remove方法删除 iterator.remove(); } else { // 继续迭代 iterator.next(); } } ``` 在`for-each`循环中,我们不能直接循环体内部使用`break`或`continue`语句来跳过迭代器的`next`方法调用,这样导致`NoSuchElementException`异常。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值