When adding another object, Java util. ConcurrentModificationException

I am experiencing this exception What's wrong with my code?

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



}

This is a stack trace

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)

Solution

You cannot modify the collection being iterated This may throw a concurrentmodificationexception Although it works sometimes, it is not guaranteed to work every time

If you want to add or remove content from the list, you need to use iterator or listiterator as the list And use the listiterator #add method to add anything to the list Even in your iterator, if you try to use list Add or list Remove, you'll get the exception, too, because it makes no difference You should use the iterator method

See these posts for how to use it: –

> Java : ConcurrentModificationException while iterating over list > Iterating through a Collection,avoiding ConcurrentModificationException when removing in loop

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>