• Java中ArrayList循环遍历并删除元素的陷阱


    ava中的ArrayList循环遍历并且删除元素时经常不小心掉坑里,昨天又碰到了,感觉有必要单独写篇文章记一下。

    先写个测试代码:

    Java代码  收藏代码
    1. import java.util.ArrayList;  
    2.   
    3. public class ArrayListRemove {  
    4.   
    5.     public static void main(String[] args) {  
    6.         ArrayList<String> list = new ArrayList<String>();  
    7.         list.add("a");  
    8.         list.add("bb");  
    9.         list.add("bb");  
    10.         list.add("ccc");  
    11.         list.add("ccc");  
    12.         list.add("ccc");  
    13.   
    14.         remove(list);  
    15.   
    16.         for (String s : list) {  
    17.             System.out.println("element : " + s);  
    18.         }  
    19.     }  
    20.   
    21.     public static void remove(ArrayList<String> list) {  
    22.         // TODO:  
    23.     }  
    24. }  

    错误写法示例一:

    Java代码  收藏代码
    1. public static void remove(ArrayList<String> list) {  
    2.     for (int i = 0; i < list.size(); i++) {  
    3.         String s = list.get(i);  
    4.         if (s.equals("bb")) {  
    5.             list.remove(s);  
    6.         }  
    7.     }  
    8. }  

    这种最普通的循环写法执行后会发现有一个“bb”的字符串没有删掉。

    错误写法示例二:

    Java代码  收藏代码
    1. public static void remove(ArrayList<String> list) {  
    2.     for (String s : list) {  
    3.         if (s.equals("bb")) {  
    4.             list.remove(s);  
    5.         }  
    6.     }  
    7. }  

    这种for each写法会发现报出著名的并发修改异常java.util.ConcurrentModificationException。

    要分析产生上述错误现象的原因唯有翻一翻jdk的ArrayList源码,先看下ArrayList中的remove方法(注意ArrayList中的remove有两个同名方法,只是入参不同,这里看的是入参为Object的remove方法)是怎么实现的:

    Java代码  收藏代码
    1. public boolean remove(Object o) {  
    2.     if (o == null) {  
    3.         for (int index = 0; index < size; index++)  
    4.             if (elementData[index] == null) {  
    5.                 fastRemove(index);  
    6.                 return true;  
    7.             }  
    8.     } else {  
    9.         for (int index = 0; index < size; index++)  
    10.             if (o.equals(elementData[index])) {  
    11.                 fastRemove(index);  
    12.                 return true;  
    13.             }  
    14.     }  
    15.     return false;  
    16. }  

    按一般执行路径会走到else路径下最终调用faseRemove方法:

    Java代码  收藏代码
    1. private void fastRemove(int index) {  
    2.     modCount++;  
    3.     int numMoved = size - index - 1;  
    4.     if (numMoved > 0)  
    5.         System.arraycopy(elementData, index+1, elementData, index,  
    6.                          numMoved);  
    7.     elementData[--size] = null; // Let gc do its work  
    8. }  

    可以看到会执行System.arraycopy方法,导致删除元素时涉及到数组元素的移动。针对错误写法一,在遍历第二个元素字符串bb时因为符合删除条件,所以将该元素从数组中删除,并且将后一个元素移动(也是字符串bb)至当前位置,导致下一次循环遍历时后一个字符串bb并没有遍历到,所以无法删除。

    针对这种情况可以倒序删除的方式来避免:

    Java代码  收藏代码
    1. public static void remove(ArrayList<String> list) {  
    2.     for (int i = list.size() - 1; i >= 0; i--) {  
    3.         String s = list.get(i);  
    4.         if (s.equals("bb")) {  
    5.             list.remove(s);  
    6.         }  
    7.     }  
    8. }  

    因为数组倒序遍历时即使发生元素删除也不影响后序元素遍历。

    而错误二产生的原因却是foreach写法是对实际的Iterable、hasNext、next方法的简写,问题同样处在上文的fastRemove方法中,可以看到第一行把modCount变量的值加一,但在ArrayList返回的迭代器(该代码在其父类AbstractList中):

    Java代码  收藏代码
    1. public Iterator<E> iterator() {  
    2.     return new Itr();  
    3. }  

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

    Java代码  收藏代码
    1. public E next() {  
    2.     checkForComodification();  
    3.     try {  
    4.         E next = get(cursor);  
    5.         lastRet = cursor++;  
    6.         return next;  
    7.     } catch (IndexOutOfBoundsException e) {  
    8.         checkForComodification();  
    9.         throw new NoSuchElementException();  
    10.     }  
    11. }  

    第一行checkForComodification方法:

    Java代码  收藏代码
    1. final void checkForComodification() {  
    2.     if (modCount != expectedModCount)  
    3.         throw new ConcurrentModificationException();  
    4. }  

    这里会做迭代器内部修改次数检查,因为上面的remove(Object)方法把修改了modCount的值,所以才会报出并发修改异常。要避免这种情况的出现则在使用迭代器迭代时(显示或foreach的隐式)不要使用ArrayList的remove,改为用Iterator的remove即可。

    Java代码  收藏代码
    1. public static void remove(ArrayList<String> list) {  
    2.     Iterator<String> it = list.iterator();  
    3.     while (it.hasNext()) {  
    4.         String s = it.next();  
    5.         if (s.equals("bb")) {  
    6.             it.remove();  
    7.         }  
    8.     }  
    9. }  
  • 相关阅读:
    C++模板学习之优先队列实现
    static 和const分别怎么用,类里面static和const可以同时修饰成员函数吗?
    C和C++的区别
    C++多态例子_虚函数
    转:master公式(主方法)
    C++11最常用的新特性如下
    转:哈夫曼树详解
    linux shell脚本
    linux 正则表达式
    linux shell命令
  • 原文地址:https://www.cnblogs.com/zquan/p/9705054.html
Copyright © 2020-2023  润新知