How does java "enhanced for" work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 27

How does java "enhanced for" work?

what is its equivalent implementation? what happens if I manipulate content of the list inside the loop?

23rd May 2018, 6:27 PM
Amir
Amir - avatar
6 Answers
+ 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
23rd May 2018, 10:16 PM
Dan Walker
Dan Walker - avatar
+ 21
Boem Shakalaka : I know how to write them! I am looking for its implementation in Java somehow.
23rd May 2018, 6:35 PM
Amir
Amir - avatar
+ 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.
23rd May 2018, 6:39 PM
***
*** - avatar
+ 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?
24th May 2018, 11:28 PM
D B
D B - avatar
+ 1
It’s just syntactic sugar for normal for loops
23rd May 2018, 7:34 PM
Max
Max - avatar
+ 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.
25th May 2018, 8:05 AM
Apple Blossom
Apple Blossom - avatar