如何在迭代时使用for-each循环而不使用ConcurrentModificationException修改集合? [英] How to modify a Collection while iterating using for-each loop without ConcurrentModificationException?
本文介绍了如何在迭代时使用for-each循环而不使用ConcurrentModificationException修改集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我在使用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
.
这篇关于如何在迭代时使用for-each循环而不使用ConcurrentModificationException修改集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文