添加另一个对象时java.util.ConcurrentModificationException [英] java.util.ConcurrentModificationException when adding another object
问题描述
我正在遭遇这个例外。我的代码有什么问题?
我只想在另一个 ArrayList中分离Person的重复名称
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;
}
}
这是堆栈跟踪
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
。虽然它有时会起作用,但并不能保证每次都能正常工作。
You cannot modify the collection
you are iterating on. That might throw a ConcurrentModificationException
. Though it might work sometimes, but it is not guaranteed to work everytime.
如果要添加或删除列表中的内容,则需要使用 Iterator
或 ListIterator
列表。并使用 ListIterator #add
方法在列表中添加任何内容。即使在你的迭代器
中,如果你试图使用 List.add
或 List.remove
,您将获得该异常,因为这没有任何区别。您应该使用 iterator
的方法。
If you want to add, or remove something from your list, you need to use an Iterator
, or ListIterator
for your list. And use ListIterator#add
method to add anything in your list. Even if in your iterator
, if you try to use List.add
or List.remove
, you will get that exception, because that doesn't make any difference. You should use the methods of iterator
.
请参阅这些帖子以了解如何使用它: -
See these posts to understand how to use it: -
- Java : ConcurrentModificationException while iterating over list
- Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop
这篇关于添加另一个对象时java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!