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 Mikezx6r for In detail, how does the 'for each' loop work in Java?

$
0
0

The construct for each is also valid for arrays. e.g.

String[] fruits = new String[] { "Orange", "Apple", "Pear", "Strawberry" };for (String fruit : fruits) {    // fruit is an element of the `fruits` array.}

which is essentially equivalent of

for (int i = 0; i < fruits.length; i++) {    String fruit = fruits[i];    // fruit is an element of the `fruits` array.}

So, overall summary:
[nsayer] The following is the longer form of what is happening:

for(Iterator<String> i = someList.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.

[Denis Bueno]

It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.


Viewing all articles
Browse latest Browse all 30

Trending Articles



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