嵌套迭代遍历列表,然后是最终删除 [英] Nested iterating through list followed by an eventual deletion

查看:126
本文介绍了嵌套迭代遍历列表,然后是最终删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过循环遍历列表(嵌套循环)进行迭代。请考虑以下代码:

I'm trying to iterate throuh a list while already looping through it (nested loops). Consider the code below:

ArrayList<Integer> list = new ArrayList<Integer>(); // add some values to it

for(int i : list) { // ConcurrentModificationException

   Iterator iterator = list.iterator();

   while(iterator.hasNext()) {

      int n = iterator.next();

      if(n % i == 0) {
         iterator.remove();
      }

   }

}

上面的示例导致ConcurrentModificationException。当然,移除元素的条件只是一个例子。

The example above results in a ConcurrentModificationException. The condition to remove an element is, of course, just an example.

我确定我只是遗漏了一些东西;但是我应该如何构建一个在Java中实现同样的东西的循环而不抛出异常?

I'm sure I'm just missing something; but how should I construct a loop that achieves the same thing in Java without throwing an exception?

推荐答案

当你迭代它导致execption时,显然修改 list
您可以使用另一个列表来维护要删除的元素列表,并在最后删除它们。

Obviously modifying list when you iterate over it causing the execption. You can use another list to maintain the list of elements to be removed and remove them at the end.

ArrayList<Integer> list = new ArrayList<Integer>(); // add some values to it
ArrayList<Integer> del = new ArrayList<Integer>(); // Elements to be deleted

for(int i : list) { // ConcurrentModificationException
   Iterator iterator = list.iterator();
   while(iterator.hasNext()) {    
      int n = iterator.next();
      if(n % i == 0) {
          del.add(n);      
      }
   }
}

list.removeALL(del);

这篇关于嵌套迭代遍历列表,然后是最终删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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