+ 27
How does java "enhanced for" work?
what is its equivalent implementation? what happens if I manipulate content of the list inside the loop?
6 ответов
+ 2
Internally an iterator is created and I don't believe this can be modified during the loop (this iterator doesn't support remove operation). You can modify the mutable objects such an iterable may have though.
When using the traditional for loop you often access the objects through array [index] or get(index). The enhanced loop makes this easier by giving you a reference to the object immediately. You can't do as many 'complex' operations by playing around with indexes or looking ahead/back as easily but it is a much cleaner way to iterate simply through a collection.
Basically, if you're only doing things to each of the elements of a list, or searching through a list to find a particular object that satisfies a condition, use an enhanced for loop
+ 21
Boem Shakalaka : I know how to write them! I am looking for its implementation in Java somehow.
+ 2
Well it's much more readable when you are iterating over a list with items then a normal for loop. (Feels more like a for loop is supose to be too)
And maybe some optimalizations but you can Google for that.
+ 2
It would be like:
int [] arr = {0,9,7,7,7,7,}
for (int i = 0; i < arr.length();i++){
int p = arr[i];
System.out.println (p);
}
is the same as
for (int p : arr) {
System.out.println (p);
}
Was this the answer you wanted?
+ 1
It’s just syntactic sugar for normal for loops
+ 1
A java iterator basically serves as an "error free" way of importing everything from given a method inside the FOR without having to write it again.