Several times I came across cases where the for-each loop caused problems, including exceptions and crashes, and for(it=list.iterator;it.hasNext();)worked without any problems. This includes changing the collection (which I know should not happen for everyone, but I don’t know why), as well as in other cases when I clone the material. I can’t recall any concrete example when I just thought about it.
for(it=list.iterator;it.hasNext();)
Is it not for everyone just a shortcut for the second type of cycle that I indicated? Can anyone explain what the difference is?
for-eachis just syntactic sugar introduced in java 1.5. It uses an iterator obtained from Iterablebehind the scene.
for-each
Iterable
, , - . , . Iterator. ConcurrentModificationException. ( ).
Iterator
ConcurrentModificationException
- Iterator.remove() ( ). .
Iterator.remove()
. , , . , Iterator.remove().
, foreach remove. remove. foreach , remove.
foreach
remove
. Foreach . .