J2SE 1.5 provides another form of a for loop. With this form of a for loop, you can iterate over the types of objects such as arrays and collection in a simpler way. This article describes how to use this loop in a specific way, explaining how to define a class that can be traversed in this way, and explain some of the common problems with this mechanism.
In a Java program, to "process"--or say, "traversal"--an element in an array or collection, is typically implemented using a for loop (and, of course, it's not not possible to use other kinds of loops, just because the word for this is a shorter length, Or because the meaning of the word "for" is better than this one, in which case the For loop is much more commonly used than other loops.
For traversing an array, the loop typically takes this approach:
Listing 1: The traditional way to traverse an array
/* 建立一个数组 */
int[] integers = {1, 2, 3, 4};
/* 开始遍历 */
for (int j = 0; j < integers.length; j++) {
int i = integers[j];
System.out.println(i);
}
And for traversing the collection object, the loop is usually in this form:
Listing 2: The traditional way to traverse collection objects
/* 建立一个Collection */
String[] strings = {"A", "B", "C", "D"};
Collection stringList = java.util.Arrays.asList(strings);
/* 开始遍历 */
for (Iterator itr = stringList.iterator(); itr.hasNext();) {
Object str = itr.next();
System.out.println(str);
}
In the latest version of the Java language,--j2se 1.5, another form of a For loop is introduced. With this form of a for loop, it is now possible to traverse the work in a simpler way.
1. The second for loop
Not strictly speaking, Java's second for loop is basically such a format:
for (loop variable type loop variable name: object to be traversed) loop body
With this syntax, an operation that iterates through an array can be written like this:
Listing 3: A simple way to traverse an array
/* 建立一个数组 */
int[] integers = {1, 2, 3, 4};
/* 开始遍历 */
for (int i : integers) {
System.out.println(i);/* 依次输出“1”、“2”、“3”、“4” */
}
The For loop used here is considered to be such a form during compilation: