user1862770
user1862770

Reputation: 317

Java concurrent modification

I have the following code:

System.out.println(dislist.size());

for (int k = 0; k < 10; k++) {
    System.out.println(k + dislist.get(k).first + dislist.get(k).second);

    if (!dislist.get(k).first.equals(Nodename)) {
        if (dislist.get(k).first.equals(myfirst) ||
            dislist.get(k).first.equals(mysecond) ||
            dislist.get(k).second.equals(myfirst) ||
            dislist.get(k).second.equals(mysecond)) {
                dislist.remove(k);                    
            }
        }
    }
}

The Problem is: the print at the beginning clearly says that dislist.size() is 10. However, I get an array out of bounds exception, telling me that the size of the list is no more than 6. And yes, I DID add new objects to the list a few lines before that. I guess when the loop starts that has not been finished yet. Is there a way to force Java (within the same method) to start the loop only when there is really 10 objects in the list?

Upvotes: 2

Views: 101

Answers (2)

Mike
Mike

Reputation: 2434

You're removing elements from the List as you iterate though it. That's the reason the size is changing.

dislist.remove(k);

Create a new list, and add each element you want to remove to it. After your loop is finished, use disList.removeAll(listOfElementsToRemove) to remove them all at once.

Upvotes: 5

Adam Sznajder
Adam Sznajder

Reputation: 9206

Iterator<YourClass> iter = dislist.iterator();
while (iter.hasNext()) {
     YourClass obj = iter.next();
     if (/* your expression */) {
          iter.remove();
     }
}

Upvotes: 4

Related Questions