java - 获取并发修改异常只是为了尝试读取 ArrayList 的元素

标签 java exception concurrency

我知道当我尝试修改或从列表中删除时我会得到这个异常,但只是为了从中读取?!这里的解决方案是什么?

public boolean recieveHello(Neighbor N, HelloMsg H) {
        Iterator<Neighbor> I = NTable.iterator();
        Iterator<Neighbor> J = NTable.iterator();
        if(!J.hasNext()) {
            this.NTable.add(N);
        }

        while(I.hasNext()) {
            if(I.next().nid == N.getnid()) {  /*EXCEPTION IS HERE*/
                //case where the node is already present in the NTable
            }
            else {
                N.setnhrc(0);  
                this.NTable.add(N);
                //case where the node is to be added to the NTable
            }
        }
        return true;
    }

顺便说一下,我必须提到 NTable 是一个 arrayList 并且是类的成员,其方法是

编辑

我使用::解决了这个问题

public boolean recieveHello(Neighbor N, HelloMsg H) {
        Iterator<Neighbor> I = NTable.iterator();
        Iterator<Neighbor> J = NTable.iterator();
        if(!J.hasNext()) {
            this.NTable.add(N);
        }
        boolean flag = false;
        for (int i=0; i<NTable.size(); i++) {
            if(NTable.get(i).nid == N.getnid()) {
                //case where the node is already present in the NTable
            }
            else {
                flag = true;
                N.setnhrc(0);  
                this.NTable.add(N);
                //case where the node is to be added to the NTable
            }
        }
        if(flag == true) {

        }
        return true;
    }

最佳答案

好吧,当你说

  this.NTable.add(N);

因此,改为在单独的列表中跟踪要添加的项目,然后在第一次迭代后追加这些项目。

关于java - 获取并发修改异常只是为了尝试读取 ArrayList 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9968602/

相关文章:

python - 放入 Python 异常消息的详细信息量的约定?

PHP 在保存文件时捕获错误

java - 寻找令人惊讶的并发 Java 程序

java - 缺少服务器异常 Spring Boot

java - 设置 MetaspaceSize 的指南 - java 8

java - 如何为 R 设置 `Java headers gen.:` (安装 `rJava` )

java - 不确定 volatile 的这种用法是否有意义,似乎有同样的问题

java - 复杂条件查询: using JPA instead of NativeQuery

java - 更改数组列表中对象的类

java - "In a distributed environment, one does not use multithreding"- 为什么?