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