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

2024-02-21

我正在遭受这个例外。我的代码有什么问题? 我只想将另一个人的重复名字分开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;
    }



}

这是堆栈跟踪

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)

您不能修改collection你正在迭代。这可能会抛出一个ConcurrentModificationException。虽然它有时可能有效,但不能保证每次都有效。

如果您想在列表中添加或删除某些内容,则需要使用Iterator, or ListIterator为您的清单。并使用ListIterator#add http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#add(E)方法在列表中添加任何内容。即使在你的iterator,如果你尝试使用List.add or List.remove,您将得到该异常,因为这没有任何区别。你应该使用以下方法iterator.

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

  • Java:迭代列表时出现 ConcurrentModificationException https://stackoverflow.com/questions/6596673/java-concurrentmodificationexception-while-iterating-over-list
  • 迭代集合,避免循环删除时出现 ConcurrentModificationException https://stackoverflow.com/questions/223918/efficient-equivalent-for-removing-elements-while-iterating-the-collection
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

添加另一个对象时出现 java.util.ConcurrentModificationException 的相关文章

随机推荐