Consider:
List<String> someList = new ArrayList<String>(); // add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) { System.out.println(item); }
What would the equivalent for
loop look like without using the for each syntax?
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.
In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop.
for (Iterator<String> i = someIterable.iterator(); i.hasNext();) { String item = i.next(); System.out.println(item); }
Note that if you need to use i.remove();
in your loop, or access the actual iterator in some way, you cannot use the for ( : )
idiom, since the actual iterator is merely inferred.
As was noted by Denis Bueno, this code works for any object that implements the Iterable
interface.
Also, if the right-hand side of the for (:)
idiom is an array
rather than an Iterable
object, the internal code uses an int index counter and checks against array.length
instead. See the Java Language Specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With