0

Is it true that it is not safe to insert into a list while iterating through it? Thoughts? I'm not sure personally...

Ankit
  • 6,554
  • 6
  • 49
  • 71
MakMak
  • 81
  • 3
  • 8

2 Answers2

1

If you are iterating through a collection using an Iterator object, then changing the underlying collection will create a ConcurrentModificationError that will crash the code. This applies even if you are using a for-each loop, because this type of loop implicitly declares an Iterator.

More information on ConcurrentModificationException.

Jimmy Lee
  • 1,001
  • 5
  • 12
1

As I expected it throw ConcurrentModificationException. I test it on simple example:

public class Test {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        for(Iterator<Integer> it = list.iterator(); it.hasNext();it.next()){
            System.out.println(it.toString());
            list.add(4);
        }
    }
}

changen ArrayList to LinkedList give the same result. If I remember exactly only remove operation are valid

Aliaksei Bulhak
  • 6,078
  • 8
  • 45
  • 75