gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:19:11 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com