For-each and for loops

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.

Is it not for everyone just a shortcut for the second type of cycle that I indicated? Can anyone explain what the difference is?

0
source share
2 answers

for-eachis just syntactic sugar introduced in java 1.5. It uses an iterator obtained from Iterablebehind the scene.

, , - . , . Iterator. ConcurrentModificationException. ( ).

- Iterator.remove() ( ). .

. , , . , Iterator.remove().

+3

, foreach remove. remove. foreach , remove.

. Foreach . .

+5

All Articles