
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at http://cnx.org/contents/402b20ad-c01f-45f1-9743-05eadb1f710e@37.6
An exceedingly common for-loop to write is the following;
Stuff[] s array = new Stuff[n]; // fill s array with values for(int i = 0; i < s array.length; i++) { // do something with s array[i] }
Essentially, the loop does some invariant processing on every element of the array. To make life easier, Java implements the for-each loop, which is just an alternate for loop syntax:
Stuff[] s array = new Stuff[n]; // fill s array with values for(Stuff s:s array) { // do something with s }
Simpler, eh?
It turns out that the for-each loop is not simply relegated to array. Any class that implements the Iterable interface will work. This is discussed in another module, as it involves the use of generics.
- 瀏覽次數:1458