【发布时间】:2013-03-01 08:08:06
【问题描述】:
我正在为我的大学课程玩一些代码,并从
更改了一个方法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);
}
但新方法不断给出并发修改错误。我该如何解决这个问题?为什么会这样?
【问题讨论】:
-
这是三个被问到最多的 Java 问题之一。您必须使用迭代器并调用
iterator.remove。 -
您在迭代列表时正在更改列表,java 集合不允许这样做。完整的解释可以找到here