-2

If we have 2 ways to iterate :

First :

Object ob;
ArrayList<Obect> list;
for(int i=0;i<list.size();i++)
{ //Todo}

Second :

Object ob;
ArrayList<Obect> list;
for(Object o:list)
{ //Todo}

So what are the differences ? I found that in second case , if try to remove object in this cycle , I get a concurrent modification exception.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
user1633277
  • 510
  • 2
  • 7
  • 14
  • 4
    Look at the [docs](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) for more information. – Vivin Paliath Jul 09 '13 at 18:13
  • The first case isn't usually a good choice for removing an object either. Consider what happens, when you remove the object at the current index, to the remaining items in the list and the loop index. – Andy Thomas Jul 09 '13 at 18:20

2 Answers2

6

In your first example, you are iterating through the list yourself. You must take responsibility for maintaining the state of your iteration if you modify the collection during iteration.

In your second example, the "foreach" loop you are using uses an implicit Iterator behind the scenes. If you modify the collection yourself with an active Iterator, you will get a ConcurrentModificationException.

If you must remove an element while using an Iterator, then use an explicit Iterator:

for(Iterator<Object> itr = list.iterator(); itr.hasNext())
{
    Object o = itr.next():
    if (decideToRemove)
        itr.remove();
}

The Iterator's remove operation is allowed to remove an element without throwing a ConcurrentModificationException.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

The proper way to remove from collections is to use a 3rd kind of loop that looks like this:

    for (Iterator<Object> iterator = new ArrayList<>().iterator(); iterator.hasNext(); ) {
        Object o = iterator.next();
        if (someCondition())
            iterator.remove();
    }
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356