我正在玩我的大学课程的一些代码,并改变了方法
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;
}
Run Code Online (Sandbox Code Playgroud)
至:
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);
}
Run Code Online (Sandbox Code Playgroud)
但是新方法不断给出并发修改错误.我怎样才能解决这个问题,为什么会这样呢?
Zut*_*tty 20
这是因为您在执行后继续遍历列表remove()
.
您正在同时读取和写入列表,这会破坏foreach循环下的迭代器的契约.
Iterator.remove()
for(Iterator<Student> iter = students.iterator(); iter.hasNext(); ) {
Student student = iter.next();
if(studentName.equalsIgnoreCase(student.getName()) {
iter.remove();
}
}
Run Code Online (Sandbox Code Playgroud)
它描述如下:
返回迭代中的下一个元素.
NoSuchElementException
如果迭代没有更多元素,则抛出.
您可以Iterator.hasNext()
用来检查是否有可用的下一个元素.