foreach遍历list删除元素

from:foreach遍历list删除元素一定会报错?


foreach遍历list集合删除某些元素一定会报错吗,来,先上一段代码:
1)报错啦
  1. List list = new ArrayList();

  2.        list.add("1");

  3.        list.add("2");

  4.        list.add("3");

  5.        list.add("4");

  6.        list.add("5");

  7.        for (String item : list) {

  8.            if (item.equals("3")) {

  9.                System.out.println(item);

  10.                list.remove(item);

  11.            }

  12.        }

  13.        System.out.println(list.size());

理所应当,控制台就愉快的报出了java.util.ConcurrentModificationException。
这是怎么回事,然后去看了看这个异常,才发现自己果然还是太年轻啊。
我们都知道增加for循环即foreach循环其实就是根据list对象创建一个iterator迭代对象,用这个迭代对象来遍历list,相当于list对象中元素的遍历托管给了iterator,如果要对list进行增删操作,都必须经过iterator。

每次foreach循环时都有以下两个操作:

1.iterator.hasNext(); //判读是否有下个元素

2.item = iterator.next();//下个元素是什么,并把它赋给item。
首先,我们来看看这个异常信息是什么。


  1. public boolean hasNext() {

  2.             return cursor != size;

  3.         }

  4.         @SuppressWarnings("unchecked")

  5.         public E next() {

  6.             checkForComodification();//此处报错

  7.             int i = cursor;

  8.             if (i >= size)

  9.                 throw new NoSuchElementException();

  10.             Object[] elementData = ArrayList.this.elementData;

  11.             if (i >= elementData.length)

  12.                 throw new ConcurrentModificationException();

  13.             cursor = i + 1;

  14.             return (E) elementData[lastRet = i];

  15.         }

  16.     final void checkForComodification() {

  17.             if (modCount != expectedModCount)

  18.                 throw new ConcurrentModificationException();

  19.         }

可以看到是进入checkForComodification()方法的时候报错了,也就是说modCount != expectedModCount。具体的原因,是在于foreach方式遍历元素的时候,是生成iterator,然后使用iterator遍历。在生成iterator的时候,会保存一个expectedModCount参数,这个是生成iterator的时候List中修改元素的次数。如果你在遍历过程中删除元素,List中modCount就会变化,如果这个modCount和exceptedModCount不一致,就会抛出异常,这个是为了安全的考虑。看看list的remove源码:
  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.     }

看,并没有对expectedModCount进行任何修改,导致expectedModCount和modCount不一致,抛出异常。所以,遍历list删除元素一律用Iterator这样不会报错,如下:
  1. Iterator it = list.iterator();

  2.         while(it.hasNext()){

  3.             if(it.next().equals("3")){

  4.                 it.remove();

  5.             }

  6.         }

看看Iterator的remove()方法的源码,是对expectedModCount重新做了赋值处理的,如下:
  1. public void remove() {

  2.             if (lastRet < 0)

  3.                 throw new IllegalStateException();

  4.             checkForComodification();

  5.             try {

  6.                 ArrayList.this.remove(lastRet);

  7.                 cursor = lastRet;

  8.                 lastRet = -1;

  9.                 expectedModCount = modCount;//处理expectedModCount

  10.             } catch (IndexOutOfBoundsException ex) {

  11.                 throw new ConcurrentModificationException();

  12.             }

  13.         }

这样的话保持expectedModCount = modCount相等,就不会报出错了。
2)是不是foreach所有的list删除操作都会报出这个错呢

其实不一定,有没有发现如果删除的元素是倒数第二个数的话,其实是不会报错的,为什么呢,来一起看看。

之前说了foreach循环会走两个方法hasNext() 和next()。如果不想报错的话,只要不进next()方法就好啦,看看hasNext()的方法。
  1. public boolean hasNext() {

  2.        return cursor != size;

  3. }

那么就要求hasNext()的方法返回false了,即cursor == size。其中cursor是Itr类(Iterator子类)中的一个字段,用来保存当前iterator的位置信息,从0开始。cursor本身就是游标的意思,在数据库的操作中用的比较多。只要curosr不等于size就认为存在元素。由于Itr是ArrayList的内部类,因此直接调用了ArrayList的size字段,所以这个字段的值是动态变化的,既然是动态变化的可能就会有问题出现了。

我们以上面的代码为例,当到倒数第二个数据也就是”4”的时候,cursor是4,然后调用删除操作,此时size由5变成了4,当再调用hasNext判断的时候,cursor==size,就会调用后面的操作直接退出循环了。我们可以在上面的代码添加一行代码查看效果:
  1. for (String item : list) {

  2.         System.out.println(item);

  3.            if (item.equals("4")) {

  4.                list.remove(item);

  5.            }

  6. }

输出是:1 2 3 4
这样的话就可以看到执行到hasNext()方法就退出了,也就不会走后面的异常了。

由此可以得出,用foreach删除list元素的时候只有倒数第二个元素删除不会报错,其他都会报错,所以用Iterator啦。

never too late!    

参考:http://rongmayisheng.com/post/%E7%A0%B4%E9%99%A4%E8%BF%B7%E4%BF%A1java-util-arraylist%E5%9C%A8foreach%E5%BE%AA%E7%8E%AF%E9%81%8D%E5%8E%86%E6%97%B6%E5%8F%AF%E4%BB%A5%E5%88%A0%E9%99%A4%E5%85%83%E7%B4%A0
http://blog.csdn.net/Jywangkeep_/article/details/48754189