Dineshkumar
Dineshkumar

Reputation: 4245

ConcurrentModificationException in removing element in ArrayList [Using iterator.remove()]

i know that we shouldn't modify the ArrayList during iteration.

But i'm using Iterator to iterate over list and iterator.remove() to remove the element but still results in ConcurrentModification Exception.

My program is not multithreaded.

I've many arraylist [class contains it and i'm processing many array of objects]

for(int i=0;i<obj.length;i++)
{
    if(k==i) continue;

    it = obj[i].arraylist.iterator();

    while(it.hasNext()){
    value = it.next();

      if(condn)  {
       it.remove();
       obj[k].arraylist.add(value);
       //k and i are not same 

      }

    }

}

Upvotes: 0

Views: 287

Answers (2)

WoooHaaaa
WoooHaaaa

Reputation: 20470

You can only modify the List during iteration using it variable.

Upvotes: 0

Amin Abu-Taleb
Amin Abu-Taleb

Reputation: 4511

"Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."

You can remove objects but not add new ones during the iteration, that's why you get that ConcurrentModificationException.

http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html

Edit: You can also check:

if(k==i || obj[i].arraylist == obj[k].arraylist) continue;

Upvotes: 1

Related Questions