I’m suffering on this exception. What’s the problem on my code?
I just want to separate Person’s duplicate name in another 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;
}
}
Here’s the stacktrace
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)
You cannot modify the
collectionyou are iterating on. That might throw aConcurrentModificationException. Though it might work sometimes, but it is not guaranteed to work everytime.If you want to add, or remove something from your list, you need to use an
Iterator, orListIteratorfor your list. And useListIterator#addmethod to add anything in your list. Even if in youriterator, if you try to useList.addorList.remove, you will get that exception, because that doesn’t make any difference. You should use the methods ofiterator.See these posts to understand how to use it: –