我在这个例外上受苦。我的代码有什么问题?我只想将 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;
}
}
这是堆栈跟踪
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)