添加另一个对象时java.util.ConcurrentModificationException

8 java

我正在遭遇这个例外.我的代码有什么问题?我只想将Person的重复名称分开ArrayList

public class GlennTestMain
{

    static ArrayList<Person> ps;

    static ArrayList<Person> duplicates;
    public static void main(String[] args)
    {
        ps = new ArrayList<GlennTestMain.Person>();

        duplicates = new ArrayList<GlennTestMain.Person>();

        noDuplicate(new Person("Glenn", 123));
        noDuplicate(new Person("Glenn", 423));
        noDuplicate(new Person("Joe", 1423)); // error here


        System.out.println(ps.size());
        System.out.println(duplicates.size());
    }

    public static void noDuplicate(Person p1)
    {
        if(ps.size() != 0)
        {
            for(Person p : ps)
            {
                if(p.name.equals(p1.name))
                {
                    duplicates.add(p1);
                }
                else
                {
                    ps.add(p1);
                }
            }
        }
        else
        {
            ps.add(p1);
        }
    }

    static class Person
    {
        public Person(String n, int num)
        {
            this.name = n;
            this.age = num;
        }
        String name;
        int age;
    }



}
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at hk.com.GlennTestMain.noDuplicate(GlennTestMain.java:41)
at hk.com.GlennTestMain.main(GlennTestMain.java:30)
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 17

您无法修改collection您正在迭代的内容.这可能会抛出一个ConcurrentModificationException.虽然它有时会起作用,但并不能保证每次都能正常工作.

如果要添加或删除列表中的内容,则需要使用IteratorListIterator列表.并使用ListIterator#add方法在列表中添加任何内容.即使在你的iterator,如果你试图使用List.addList.remove,你将得到该例外,因为这没有任何区别.你应该使用的方法iterator.

请参阅这些帖子以了解如何使用它: -


Ami*_*nde 7

原因?

迭代器返回的ArrayList的fail-fast自然界中。

此类的迭代器和listIterator方法返回的迭代器为fail-fast:如果在迭代器创建后的任何时间对列表进行结构修改,除了通过迭代器自己的 remove 或 add 方法外,迭代器将抛出一个ConcurrentModificationException. 因此,面对并发修改,迭代器快速而干净地失败,而不是在未来不确定的时间冒着任意、非确定性行为的风险。

当我不使用它时,这个迭代器来自哪里?

对于集合的增强 for 循环Iterator被使用,因此add您在迭代时无法调用方法。

所以你的循环与下面相同

for (Iterator<Entry> i = c.iterator(); i.hasNext(); ){   
Run Code Online (Sandbox Code Playgroud)

那么解决方案是什么?

您可以iterator.add();显式地而不是隐式地调用和更改基于迭代器的循环。

    String inputWord = "john";
    ArrayList<String> wordlist = new ArrayList<String>();
    wordlist.add("rambo");
    wordlist.add("john");
    for (ListIterator<String> iterator = wordlist.listIterator(); iterator
            .hasNext();) {
        String z = iterator.next();
        if (z.equals(inputWord)) {
            iterator.add("3");
        }
    }
    System.out.println(wordlist.size());
Run Code Online (Sandbox Code Playgroud)

现在在哪里可以阅读更多信息?

  1. For-Each 循环
  2. ArrayList Java 文档