0

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 

      }

    }

}

Dineshkumar
  • 4,165
  • 5
  • 29
  • 43

2 Answers2

1

"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;
Amin Abu-Taleb
  • 4,423
  • 6
  • 33
  • 50
  • Even if he is adding to another list? Mind "i" and "k" are made sure to be not the same. So I assume obj[i].arraylist and obj[k].arraylist are not the same instances, too. – Fildor Sep 05 '13 at 06:54
  • @Fildor You are sure 'i' and 'k' are different, indeed, but you can't assume that the arraylists within obj[i] and obj[k] are not the same objects. – Amin Abu-Taleb Sep 05 '13 at 07:09
  • If that is the case, then we have the flaw detected :) BTW: it should continue if the instances _are_ the same, so, it should be `obj[i].arraylist == obj[k].arraylist)` , right? – Fildor Sep 05 '13 at 07:11
0

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

WoooHaaaa
  • 19,732
  • 32
  • 90
  • 138