ArrayList循环遍历并删除元素的常见陷阱

本文深入探讨了在Java中使用ArrayList删除元素时常见的错误及其原因,包括并发修改异常和元素跳过问题。提供了四种正确的删除元素的方法,包括使用Iterator、倒序遍历、正序遍历并自减索引,以及利用Java 8的Stream流操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在工作和学习中,经常碰到删除ArrayList里面的某个元素,看似一个很简单的问题,首先请看下面的例子:

public class DuplicateAndOrderTest{

    public static void main(String[] args){
        ArrayList<String>list=new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("b");
        list.add("c");
        list.add("c");
        list.add("c");
        remove(list);
        for(String s:list){
            System.out.println("element : "+s);
        }
    }

    private static void remove(ArrayList<String> list) {

    }


}

如果要想删除list的b字符,有下面两种常见的错误例子:

错误写法实例一: 这种最普通的循环写法执行后会发现第二个“b”的字符串没有删掉:

 private static void remove(ArrayList<String> list) {
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            if (s.equals("b")) {
                list.remove(s);
            }
        }
 }

实例一的错误原因。翻开JDK的ArrayList源码,先看下ArrayList中的remove方法(注意ArrayList中的remove有两个同名方法,只是入参不同,这里看的是入参为Object的remove方法)是怎么实现的: 

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;
}


    一般情况下程序的执行路径会走到else路径下最终调用faseRemove方法
    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; // clear to let GC do its work
    }

可以看到会执行System.arraycopy方法,导致删除元素时涉及到数组元素的移动。针对错误写法一,在遍历第一个字符串b时因为符合删除条件,所以将该元素从数组中删除,并且将后一个元素移动(也就是第二个字符串b)至当前位置,导致下一次循环遍历时后一个字符串b并没有遍历到(要删除的元素相邻会有这个问题 !!!),所以无法删除。针对这种情况可以倒序删除的方式来避免,因为数组倒序遍历时即使发生元素删除也不影响后序元素遍历:

private static void remove(ArrayList<String> list) {
        for (int i = list.size() - 1; i >= 0; i--) {
            String s = list.get(i);
            if (s.equals("b")) {
                list.remove(s);
            }
        }
}

 

错误写法实例二:这种for-each写法会报出著名的并发修改异常:java.util.ConcurrentModificationException

private static void remove(ArrayList<String> list) {
        for (String s : list) {
            if (s.equals("b")) {
                list.remove(s);
            }
        }
}

错误二产生的原因却是foreach写法是对实际的Iterable、hasNext、next方法的简写,

for (String s : list) {
   System.out.println(s);       
}
 

增强for循环底层 经过反编译后得到如下
String s;
for(Iterator iterator = list.iterator(); iterator.hasNext(); System.out.println(s)){
   s = (String)iterator.next();        
}

问题同样处在上文的fastRemove方法中,可以看到第一行把modCount变量的值加一,而expectedCount值未变,但在ArrayList返回的迭代器(该代码在其父类AbstractList中):

public Iterator<E> iterator() {
        return new Itr();
}

这里返回的是AbstractList类内部的迭代器实现private class Itr implements Iterator,看这个类的next方法:

 public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
 }


这里会做迭代器内部修改次数检查,因为上面的remove(Object)方法修改了modCount的值,而expectedCount值未变, 所以才会报出并发修改异常
 final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
 }

List 移除某个元素的四种正确方式

方式一,使用 Iterator ,顺序向下,如果找到元素,则使用 remove 方法进行移除。
方式二,倒序遍历 List ,如果找到元素,则使用 remove 方法进行移除。
方式三,正序遍历 List ,如果找到元素,则使用 remove 方法进行移除,然后进行索引 “自减”。
方式四,使用jdk1.8新增的Stream流操作

 

1.Iterator 迭代器

要避免这种情况的出现则在使用迭代器迭代时(显示或for-each的隐式)不要使用ArrayList的remove,改为用Iterator的remove即可。

private static void remove(ArrayList<String> list) {
        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            String s = it.next();
            if (s.equals("b")) {
                it.remove();
            }
        }
}

2 倒序遍历

当我们倒序遍历元素的时候,无论删除元素之后的元素怎么移动,之前的元素对应的索引(index)是不会发生变化的,所以在删除元素的时候不会发生问题。

  private static void remove(ArrayList<String> list) {
    for (int i = list.size() - 1; i > 0; i--) {
      if("b".equals(list.get(i))){
        list.remove(i);
      }
    }
  }

3.正序遍历

  private static void remove(ArrayList<String> list) {
    for (int i = 0; i < list.size(); i++) {
      if("b".equals(list.get(i))){
        list.remove(i);
        i--;
      }
    }
  }

4. jdk 1.8新特性

list.stream().filter(s-> !s.equals("b")).collect(Collectors.toList());

原文: https://www.cnblogs.com/huangjinyong/p/9455163.html

          https://blog.csdn.net/zhaozuhao110/article/details/88116831

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值