Is it true that it is not safe to insert into a list while iterating through it? Thoughts? I'm not sure personally...
Asked
Active
Viewed 149 times
0
-
5"A list" is not all that helpful. Some lists may be "safe" to use in such a way, others may not. "Safe" is not particularly well defined either! – Affe Mar 27 '13 at 03:25
-
1I think it will throw an concurrentmodification exception if you modify the list directly – Arun P Johny Mar 27 '13 at 03:25
-
1See this [answer](http://stackoverflow.com/a/7409771/2024761) – Rahul Mar 27 '13 at 03:26
-
@Affe It's not possible without the iterator right? Apart from that – Thihara Mar 27 '13 at 03:40
2 Answers
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
.

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