Java并发修改异常错误 [英] Java Concurrent Modification Exception Error

查看:39
本文介绍了Java并发修改异常错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的大学课程玩一些代码并更改了

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?

推荐答案

是因为你在执行remove()后继续遍历列表.

It is because you continue traversing the list after performing remove().

您同时读取和写入列表,这违反了 foreach 循环底层迭代器的约定.

You're reading and writing to the list at the same time, which breaks the contract of the iterator underlying the foreach loop.

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.

如果迭代没有更多元素,则抛出 NoSuchElementException.

Throws NoSuchElementException if the iteration has no more elements.

您可以使用 Iterator.hasNext() 来检查是否有可用的下一个元素.

You can use Iterator.hasNext() to check if there is a next element available.

这篇关于Java并发修改异常错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆