小编典典

在java中当遍历一个集合时,删除元素如何避免发生ConcurrentModificationException异常?

java

在java中当遍历一个集合时,删除元素如何避免发生ConcurrentModificationException异常?


阅读 566

收藏
2020-01-07

共1个答案

小编典典

1576

Iterator.remove() 是安全的,可以这样使用:

List<String> list = new ArrayList<>();

// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
//     Iterator<String> iterator = list.iterator();
//     while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
    }
}

注意,这Iterator.remove()是在迭代过程中修改集合的唯一安全方法。如果在进行迭代时以任何其他方式修改了基础集合,则行为未指定。

同样,如果您有个ListIterator并想要添加项目,则可以使用[ListIterator#add](http://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#add-E-),出于相同的原因Iterator#remove ,它可以允许使用。

你的情况,你想从列表中删除,但同样的限制,如果想put成为一个Map在迭代的内容。

2020-01-08