我在为我的大学类(class)编写一些代码,并从
更改了一个方法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);
}
但是新方法一直报并发修改错误。我怎样才能解决这个问题,为什么会这样?
最佳答案
这是因为你在执行remove()
之后继续遍历列表。
您同时读取和写入列表,这打破了 foreach 循环底层迭代器的约定。
使用Iterator.remove()
for(Iterator<Student> iter = students.iterator(); iter.hasNext(); ) {
Student student = iter.next();
if(studentName.equalsIgnoreCase(student.getName()) {
iter.remove();
}
}
描述如下:
Returns the next element in the iteration.
Throws
NoSuchElementException
if the iteration has no more elements.
您可以使用 Iterator.hasNext()
来检查是否有可用的下一个元素。
关于Java并发修改异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15384486/