如何在不使用 ConcurrentModificationException 的情况下使用 for-each 循环进行迭代时修改集合? [英] How to modify a Collection while iterating using for-each loop without ConcurrentModificationException?
本文介绍了如何在不使用 ConcurrentModificationException 的情况下使用 for-each 循环进行迭代时修改集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我在使用 for-each 循环迭代集合时修改它,它会给出 ConcurrentModificationException
.有什么解决办法吗?
If I modify a Collection while iterating over it using for-each loop, it gives ConcurrentModificationException
. Is there any workaround?
推荐答案
使用 Iterator#remove
.
这是在迭代期间修改集合的唯一安全方法.有关详细信息,请参阅集合界面教程.
This is the only safe way to modify a collection during iteration. For more information, see The Collection Interface tutorial.
如果您还需要在迭代时添加元素的能力,请使用 ListIterator
.
If you also need the ability to add elements while iterating, use a ListIterator
.
这篇关于如何在不使用 ConcurrentModificationException 的情况下使用 for-each 循环进行迭代时修改集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文