Java的并发修改异常错误 [英] Java Concurrent Modification Exception Error
本文介绍了Java的并发修改异常错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
林与一些code玩弄我的大学课程,并从
Im playing around with some code for my college course and changed a method from
public boolean removeStudent(String studentName)
{
int index = 0;
for (Student student : students)
{
if (studentName.equalsIgnoreCasee(student.getName()))
{
students.remove(index);
return true;
}
index++;
}
return false;
}
要:
public void removeStudent(String studentName) throws StudentNotFoundException
{
int index = 0;
for (Student student : students)
{
if (studentName.equalsIgnoreCase(student.getName()))
{
students.remove(index);
}
index++;
}
throw new StudentNotFoundException( "No such student " + studentName);
}
但是,新方法不断给并发修改错误。我怎样才能避开这个和它为什么发生?
But the new method keeps giving a Concurrent Modification error. How can I get round this and why is it happening?
推荐答案
它,因为你继续履行后遍历列表删除()
。你正在阅读,并在同一时间,它打破了迭代器的foreach循环底层的合同写到列表中。
Its because you continue traversing the list after performing remove()
. You're reading and writing to the list at the same time, which breaks the contract of the iterator underlying the foreach loop.
尝试使用 Iterator.remove()
...
for(Iterator<Student> iter = students.iterator(); iter.hasNext(); ) {
Student student = iter.next();
if(studentName.equalsIgnoreCasee(student.getName()) {
iter.remove();
}
}
这篇关于Java的并发修改异常错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文