在ArrayList中尝试遍历时如何修复java.util.ConcurrentModificationException错误 [英] How to fix java.util.ConcurrentModificationException error when trying traverse in ArrayList
本文介绍了在ArrayList中尝试遍历时如何修复java.util.ConcurrentModificationException错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果满足条件,我正在尝试向ArrayList添加新对象。
但是当我尝试运行它时,它得到了这个ConcurrentModificationExeption。希望你可以帮助我:
public void addTaskCollection(Task t){
ListIterator< Task> iterator = this.taskCollection.listIterator();
if(this.taskCollection.isEmpty())
this.taskCollection.add(t);
while(iterator.hasNext()){
if(t.isOverlapped(iterator.next()))
this.taskCollection.add(t);
}
}
这里是exeption错误
$线程main中的异常b$ b $ $ )
在java.util.ArrayList $ Itr.next(ArrayList.java:791)
在Diary.addTaskCollection(Diary.java:36)
在Test.main(Test.java: 50)
Java结果:1
解决方案
替换您的代码为:
ListIterator< Task> iterator = this.taskCollection.listIterator();
boolean marker = false;
if(taskCollection.isEmpty())
this.taskCollection.add(t);
else {
while(iterator.hasNext()){
if(iterator.next()。isOverlapped(t)== false)
marker = true;
}
}
if(marker == true)
taskCollection.add(t);
以避免ConcurrentModificationException。
I'm trying to add new object to my ArrayList if it satisfy the condition. But it got me this ConcurrentModificationExeption when I tried to run it. Hope you could help me:
public void addTaskCollection(Task t){
ListIterator<Task> iterator = this.taskCollection.listIterator();
if(this.taskCollection.isEmpty())
this.taskCollection.add(t);
while (iterator.hasNext()){
if(t.isOverlapped(iterator.next()))
this.taskCollection.add(t);
}
}
And here is the exeption error
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at Diary.addTaskCollection(Diary.java:36)
at Test.main(Test.java:50)
Java Result: 1
解决方案
Replace your code with:
ListIterator<Task> iterator = this.taskCollection.listIterator();
boolean marker = false;
if(taskCollection.isEmpty())
this.taskCollection.add(t);
else {
while (iterator.hasNext()) {
if(iterator.next().isOverlapped(t) == false)
marker = true;
}
}
if (marker == true)
taskCollection.add(t);
to avoid ConcurrentModificationException.
这篇关于在ArrayList中尝试遍历时如何修复java.util.ConcurrentModificationException错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文