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

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

问题描述

我有一个列表,我想遍历该列表并根据某些条件删除一些记录.这就是我要做的

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

此代码生成异常.如果我使用 Iterator 那么它工作正常

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

我想我的问题是:

  1. 为什么第一段代码不起作用?

如何使第一段代码工作?

推荐答案

  1. 它不起作用,因为您正在修改一个集合,同时对其进行迭代.这意味着您正在更改其状态并同时阅读它.这会在集合内部引发意外行为,并且为了防止数据损坏,会引发异常.

  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.

你没有让它发挥作用.你必须使用迭代器.

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

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

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