Quantcast
Channel: In detail, how does the 'for each' loop work in Java? - Stack Overflow
Viewing all articles
Browse latest Browse all 30

Answer by nsayer for In detail, how does the 'for each' loop work in Java?

$
0
0
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.


Viewing all articles
Browse latest Browse all 30

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>