如何在迭代时将值添加到列表 [英] How to add values to a list while iterating it

查看:95
本文介绍了如何在迭代时将值添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的情况

List<String> xxx = new ArrayList
for(String yyy : xxx){
   for(String zzz:xyxy){
     if(!zzz.equals(yyy)){
       xxx.add(zzz);
     }
   }
}

但是我得到了java.util.ConcurrentModificationException:空异常.有人可以帮我解决这个问题吗?谁能给我另一种方法执行此操作?

But i get java.util.ConcurrentModificationException: null exception.Can anyone help me solve this issue.? Can anyone give me alternate method to perform this ?

推荐答案

查看

Looking at the ArrayList API:

此类的iterator和listIterator方法返回的迭代器是快速失败的:如果在创建迭代器之后的任何时间以任何方式对列表进行结构修改,除非通过迭代器自己的remove或add方法,否则迭代器将抛出一个ConcurrentModificationException.

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

因此,您将需要显式获取一个 ListIterator ,并使用它来正确更改您的 ArrayList .另外,我不认为您可以使用for-each循环,因为其中的迭代器与您显式检索的迭代器是分开的.我认为您必须使用while循环:

So you're going to need to explicitly get a ListIterator and use that to properly alter your ArrayList. Also, I don't believe you can use a for-each loop because the iterators in those are separate from your explicitly retrieved iterator. I think you'll have to use a while loop:

List<String> xxx = new ArrayList<>();
ListIterator<String> iterator = xxx.listIterator();
while (iterator.hasNext()) {
    String s = iterator.next();
    for (String zzz : xyxy) {
        if (!zzz.equals(s)) {
            iterator.add(zzz); //<-- Adding is done through the iterator
        }
    }
}

这篇关于如何在迭代时将值添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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