Chani
Chani

Reputation: 5165

getting concurrent modification exception just for trying to read an element of an ArrayList

I know i will get this exception when i try to modify or remove from the list, but just for reading from it ?! What is the solution here ?

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;
    }

By the way, I must mention that NTable is an arrayList and is a member of the class whose method this is

EDIT

I solved the problem using ::

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;
    }

Upvotes: 2

Views: 626

Answers (1)

FlavorScape
FlavorScape

Reputation: 14299

Well you're changing the size of the list while iterating over it when you say

  this.NTable.add(N);

So, instead keep track of which ones to add in a separate list, then append the items after the first iteration.

Upvotes: 8

Related Questions