[英]getting concurrent modification exception just for trying to read an element of an 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);
}
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);
因此,代替跟踪要添加到单独列表中的项,然后在第一次迭代后追加项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.