且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

迭代遍历和从 ArrayList 中删除元素时如何避免 java.util.ConcurrentModificationException

更新时间:2023-11-29 18:03:04

两个选项:

  • 创建一个你想要删除的值列表,添加到循环中的那个列表,然后在最后调用originalList.removeAll(valuesToRemove)
  • 在迭代器本身上使用 remove() 方法.请注意,这意味着您不能使用增强的 for 循环.
  • Create a list of values you wish to remove, adding to that list within the loop, then call originalList.removeAll(valuesToRemove) at the end
  • Use the remove() method on the iterator itself. Note that this means you can't use the enhanced for loop.

作为第二个选项的示例,从列表中删除长度大于 5 的任何字符串:

As an example of the second option, removing any strings with a length greater than 5 from a list:

List<String> list = new ArrayList<String>();
...
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
    String value = iterator.next();
    if (value.length() > 5) {
        iterator.remove();
    }
}