我正在为这个异常而苦恼。我的代码有什么问题?
我只想在另一个 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)
最佳答案
您不能修改您正在迭代的集合
。这可能会引发 ConcurrentModificationException
。虽然它有时可能会起作用,但不能保证每次都能起作用。
如果您想在列表中添加或删除某些内容,您需要为列表使用Iterator
或ListIterator
。并使用 ListIterator#add
在列表中添加任何内容的方法。即使在您的 iterator
中,如果您尝试使用 List.add
或 List.remove
,您也会得到该异常,因为那不会没有任何区别。您应该使用 iterator
的方法。
查看这些帖子以了解如何使用它:-
关于添加另一个对象时出现 java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13133688/