里面循环使用循环的ListIterator从ArrayList中删除元素 [英] Remove element from ArrayList using ListIterator in loop inside loop

查看:433
本文介绍了里面循环使用循环的ListIterator从ArrayList中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是从ArrayList中删除是这样的:

My requirement is to remove from ArrayList like this:

ArrayList<User> user = new ArrayList<User>();

ListIterator<User> outerIterator = null;
ListIterator<User> innerIterator = null;

User outer = null;
User inner = null;

for(outerIterator = user.listIterator(); outerIterator.hasNext();) {
    outer = outerIterator.next();
    for(innerIterator = user.listIterator(); innerIterator.hasNext();) {
        inner = innerIterator.next();
        if(SomeOperationOn(outer,inner)) {
            innerIterator.remove();
        }
    }
}

以上code是给予例外

Above code is giving exception

Exception in thread "main" java.util.ConcurrentModificationException

如预期,因为我想从innerIterator删除而outerIterator迭代器是同一对象(用户)上。

as expected, because I am trying to remove from innerIterator while outerIterator is Iterator on same object(user).

有没有办法在循环中使用内循环的ListIterator从ArrayList中删除元素?

Is there any way to remove element from ArrayList using ListIterator in loop inside loop?

推荐答案

在隔离,​​要求删除()上的的Iterator 是避免 ConcurrentModificationException的正确的方法去除你遍历集合的项目时。不过,你得的两个的Iterator 取值遍历相同的ArrayList 。当你调用删除() innerIterator outerIterator 的通知该列表已经改变,它抛出一个 ConcurrentModificationException的

In isolation, calling remove() on an Iterator is the proper way to avoid a ConcurrentModificationException when removing an item from a collection you're iterating. However, you have two Iterators iterating over the same ArrayList. When you call remove() on innerIterator, outerIterator notices that the list has changed, and it throws a ConcurrentModificationException.

在此情况下,如果 SomeOperationOn 表示该项目需要删除,然后而不是删除它了,店里在一个临时项目清单稍后删除。在迭代器循环完成后,调用的removeAll 通过这个临时列表中。

In this case, if SomeOperationOn indicates that the item needs to be removed, then instead of removing it right away, store inner in a temporary List of items to be removed later. After the for loop on the iterators completes, call removeAll passing this temporary list.

这篇关于里面循环使用循环的ListIterator从ArrayList中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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