Java的:异常时,在for-each循环删除列表里面记录 [英] Java: Exception when remove a record inside a List in a for-each loop

查看:138
本文介绍了Java的:异常时,在for-each循环删除列表里面记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名单,我想通过列表循环和一定条件下删除一些备案基地。下面是我做的。

 公共无效美孚(列表<酒吧GT; recordList){
     对于(酒吧酒吧:recordList){
         如果(bar.someCondition()){
              recordList.remove(巴);
         }
     }
}

这code产生异常。如果我使用iterator然后正常工作

 公共无效美孚(列表<酒吧GT; recordList){
     迭代器<酒吧GT; ITER = recordList.iterator();
     而(iter.hasNext()){
         酒吧酒吧= iter.next();
         如果(bar.someCondition()){
              iter.remove();
         }
     }
}

我想我的问题:


  1. 为什么code的第一块不起作用?


  2. 如何让我的第一块code的工作?



解决方案

  1. 它不工作,因为你正在修改的集合,而在它迭代。这意味着你正在改变其状态,并在同一时间阅读。这激起了收藏的胆意外行为,并prevent数据损坏,则抛出异常。


  2. 您不能使其工作。你必须使用迭代器。


I have a List, and I want to loop through that List and remove some record base on some condition. Here is what I do

public void foo(List<Bar> recordList){
     for(Bar bar : recordList){
         if(bar.someCondition()){
              recordList.remove(bar);
         }
     }
}

This code generate exception. If I use Iterator then it works fine

public void foo(List<Bar> recordList){
     Iterator<Bar> iter = recordList.iterator();
     while(iter.hasNext()){
         Bar bar = iter.next();
         if(bar.someCondition()){
              iter.remove();
         }
     }
}

I guess my question:

  1. Why the first piece of code does not work?

  2. How do I make the first piece of code work?

解决方案

  1. It doesn't work because you are modifying a collection WHILE iterating on it. It means you are changing its state and reading it at the same time. This provokes unexpected behaviours in the inners of the collection, and to prevent data corruption, an exception is thrown.

  2. You don't make it work. You have to use iterators.

这篇关于Java的:异常时,在for-each循环删除列表里面记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆