I have been asked to use the enhanced for
loop in my coding.
I have only been taught how to use traditional for
loops, and as such don't know about the differences between it and the enhanced for
loop.
How does an enhanced for
loop differ from a traditional for
loop in Java?
Are there any intricacies that I should look out for which tutorials tend not to mention?
An enhanced for
loop is just limiting the number of parameters inside the parenthesis.
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
Can be written as:
for (int myValue : myArray) {
System.out.println(myValue);
}
for (Object obj : list);
ArrayList<Integer> list = new ArrayList<Integer>();
list.forEach((n) -> System.out.println(n));
Source: Stackoverflow.com