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 

      }

    }

}

2
  • Please provide complete code. Commented Sep 5, 2013 at 6:51
  • Do you have a stacktrace? Looks ok to me. Commented Sep 5, 2013 at 6:52

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

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 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.
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?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.