Java 如何在迭代列表时向列表添加值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23674666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:37:03  来源:igfitidea点击:

How to add values to a list while iterating it

javaconcurrentmodification

提问by Deepak Ramakrishnan Kalidass

I Have a scenario such like this

我有这样的场景

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

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

但是我得到 java.util.ConcurrentModificationException: null 异常。谁能帮我解决这个问题。?谁能给我替代方法来执行此操作?

采纳答案by awksp

Looking at the ArrayListAPI:

查看ArrayListAPI

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.

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

So you're going to need to explicitly get a ListIteratorand 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:

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

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
        }
    }
}

回答by Dmitry Ginzburg

Add them in another list and then add that list to xxx;

将它们添加到另一个列表中,然后将该列表添加到xxx;

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

回答by WoDoSc

Don't use a foreach loop, but use a normal loop like:

不要使用 foreach 循环,而是使用普通循环,例如:

int originalSize=xxx.size();
for (int i=0;i<originalSize;i++) {
    xxx.add("New string appended at the end");
}

This allows you to iterate onlyon the items present in the list beforeyou start to iterate, and it works if your only operation on the list is to add some new item at the end of it.

这允许您开始迭代之前仅对列表中存在的项目进行迭代,并且如果您对列表的唯一操作是在其末尾添加一些新项目,则它有效。

回答by Mustafa sabir

It means you cannot access and modify your collection (List) at the same time. To do so you must use an iterator. I dont understand what xyxy is in your code. but a possible iteration and adittion of element might look like this.

这意味着您不能同时访问和修改您的收藏(列表)。为此,您必须使用迭代器。我不明白你的代码中 xyxy 是什么。但是元素的可能迭代和添加可能看起来像这样。

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

        xxx.add("hello");
        xxx.add("hi");
        xxx.add("hh");

        ListIterator<String> it = xxx.listIterator();
        while (it.hasNext()) {

            if (!it.next().equals("hi")) {
                it.remove();
                it.add("hi");

            }
        }

        System.out.println(xxx);
          }
      }

回答by user3636135

To modify a list while iterating you can declare the arraylist as "java.util.concurrent.CopyOnWriteArrayList"

要在迭代时修改列表,您可以将 arraylist 声明为“ java.util.concurrent.CopyOnWriteArrayList

public static void main(String[] args) {
    List<String> xxx = new CopyOnWriteArrayList();
    xxx.add("3");
    xxx.add("4");

    List<String> xyxy = new ArrayList();
    xyxy.add("1");
    xyxy.add("2");
    xyxy.add("3");

    for (String yyy : xxx) {
        for (String zzz : xyxy) {
            if (!zzz.equals(yyy)) {
                xxx.add(zzz);
            }
        }
    }

    System.out.println(xxx);
}