Last active
January 26, 2017 08:24
-
-
Save rshepherd/7762892 to your computer and use it in GitHub Desktop.
Examples of using Java's 'for each' loop structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
public class ForEach { | |
public static void main(String[] args) { | |
// Let's say we have a plain old array, like this one. | |
char[] array = "This is a character array.".toCharArray(); | |
// So far in class we have been looping over it by using the classic syntax | |
for(int i = 0 ; i < array.length ; ++i) { | |
char element = array[i]; | |
System.out.print(element); | |
} | |
// That works fine, but its sort of annoying to have to write all those details | |
// like counter variables and increments all the time. Its noisy code. | |
// Java 5 introduced a handy concept called 'for each' loops | |
// Using it saves us some of the trouble of writing looping code. | |
for(char element : array) { | |
System.out.println(element); | |
} | |
// The structure is as follows.. | |
// for(type nameOfElement : nameOfCollection) { | |
// code that references nameOfElement | |
// } | |
// It works for just about any of the Java collections as well. | |
List<String> list = new ArrayList<String>(); | |
list.add("much"); | |
list.add("better"); | |
for(String element : list) { | |
System.out.println(element); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment