Java for cycle several ways of writing

  • 2020-06-12 08:59:13
  • OfStack

Java for cycle several ways of writing

Summary:

J2SE 1.5 provides another form of the for cycle. With this form of the for loop, objects of types such as groups and Collection can be traversed in an easier way. This article describes how to use this loop, explains how to define your own classes that can be traversed in this way, and explains some of the common problems with this mechanism.

In Java programs, "handled by 1 � � or" through "� � a particular element in an array or Collection, 1 kind USES a for loop to realize (of course, also with other kinds of circulation is not can't, just don't know the word because for length is shorter, or because for the meaning of the word and to compare with this operation, in this time for cycle is much more common than other circulation).
For traversal groups, the loop 1 is generally written as follows:

Listing 1: The traditional way to iterate over groups


/*  To establish 1 An array  */ 
int[] integers = {1 .  2 .  3 .  4}; 
/*  To traverse the  */ 
for (int j = 0; j<integers.length; j++){ 
int i = integers[j]; 
System.out.println(i); 
} 

For traversing the Collection object, the loop usually takes the form of:

Listing 2: The traditional way to traverse an Collection object


/*  To establish 1 a Collection */ 
String[] strings = {"A" .  "B" .  "C" .  "D"}; 
Collection stringList = java.util.Arrays.asList(strings); 
/*  To traverse the  */ 
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 the for loop is introduced. With this form of the for loop, you can now traverse in a simpler way.

1. The second for cycle

Loosely speaking, the second for loop of Java basically looks like this:

for (Loop variable type loop variable name: object to be traversed) loop body

With this syntax, an operation traversing an array can be written as follows:

Listing 3: A simple way to iterate through groups


/*  To establish 1 An array  */ 
int[] integers = {1 .  2 .  3 .  4}; 
/*  To traverse the  */ 
for (int i : integers) { 
System.out.println(i);/*  Output in turn" 1 "," 2 "," 3 "," 4 "  */ 
} 

The for loop used here will be viewed at compile time as follows:

Listing 4: Equivalent code for a simple way to iterate through groups


/*  To establish 1 An array  */ 
int[] integers = {1 .  2 .  3 .  4}; 
/*  To traverse the  */ 
for (int  The variable name a  = 0;  The variable name a <integers.length;  The variable name a ++) { 
System.out.println(integers[ The variable name a ]);/*  Output in turn" 1 "," 2 "," 3 "," 4 "  */ 
} 

The variable name a here is a non-confusing name automatically generated by the compiler.

The operation of traversing 1 Collection can be written as follows:

Listing 5: A simple way to iterate over Collection


/*  To establish 1 a Collection */ 
String[] strings = {"A" .  "B" .  "C" .  "D"}; 
Collection list = java.util.Arrays.asList(strings); 
/*  To traverse the  */ 
for (Object str : list) { 
System.out.println(str);/*  Output in turn" A "," B "," C "," D "  */ 
} 

The for loop used here would be viewed at compile time as follows:

Listing 6: Equivalent code for the simple way to walk through Collection


/*  To establish 1 a Collection */ 
String[] strings = {"A" .  "B" .  "C" .  "D"}; 
Collection stringList = java.util.Arrays.asList(strings); 
/*  To traverse the  */ 
for (Iterator  The variable name b  = list.iterator();  The variable name b .hasNext();) { 
Object str =  The variable name b .next(); 
System.out.println(str);/*  Output in turn" A "," B "," C "," D "  */ 
} 

The "variable name b" here is also a non-confusing name automatically generated by the compiler.

Since the compiler of J2SE 1.5 will treat this form of the for loop as its traditional counterpart during compilation, there are no performance issues to worry about.
Reasons not to use "foreach" and "in"

Java USES "for" (instead of the more explicit "foreach") to guide this loop, commonly called "ES109en-ES110en loop", and USES ":" (instead of the more explicit "in") to split the loop variable name and the object to be traversed. That is the main reason, in order to avoid because of the introduction of new keywords, cause compatibility issues � � in Java language, not allowed to use keywords as a variable name, although the use of the name "foreach" is not very much, but 1 "in" is often used to represent the name of the input stream (such as java. lang. System class, one is called "in static properties, said" the standard input stream ").

It is possible to allow keywords to be used as generic identifiers as well, with clever design syntax that allows them to have a specific meaning only in a particular context. But this syntactically complicated strategy has not been widely adopted.

The long history of the for-ES127en cycle

The "for-each loop" is not a recent control structure. This control structure (loops are guided by "for" and "in", and loops are identified by "do" and "done") was included in Bourne shell (the first full-fledged UNIX command interpreter) when it was officially released in 1979.

2. Prevent loop variables from being modified in the loop body

By default, the compiler allows re-assignment of loop variables in the loop body of the second for loop. However, it is not recommended because it has no effect on the conditions on the outside of the loop and can cause difficulties in understanding the code.

Java provides a mechanism to block such operations at compile time. To do this, add an "final" modifier before the type of the loop variable. This will cause a compilation error if 1 is assigned to a loop variable in the body of the loop. With the help of this mechanism, it is effectively impossible to "modify loop variables in the body of the loop" intentionally or unintentionally.

Listing 7: Forbidden reassignment


int[] integers = {1 .  2 .  3 .  4}; 
for (final int i : integers) { 
i = i / 2; /*  Compile time error  */ 
} 

Note that this simply prohibits reassignment of the loop variable. Assigning a property to a loop variable, or calling a method that changes the content of a loop variable, is not prohibited.

Listing 8: Allow state modification


Random[] randoms = new Random[]{new Random(1) .  new Random(2) .  new Random(3)}; 
for (final Random r : randoms) { 
r.setSeed(4);/*  Will all Random Object is set to use the same seed  */ 
System.out.println(r.nextLong());/*  Same seeds, no 1 The same result  */ 
} 

3. Type compatibility problem

J2SE 1.5 imposes a limit of 1 on the type of loop variables to ensure that they are safely assigned at the beginning of each loop. Under these restrictions, the type of a loop variable can be selected as follows:

The type of the loop variable can be the same as the type of the element in the object to be traversed. For example, loop variables of type int are used to traverse an array of type int[], and loop variables of type Object are used to traverse an array of type Collection, etc.

Listing 9: Using a loop variable of the same type as the element in the array to be traversed


int[] integers = {1 .  2 .  3 .  4}; 
for (int i : integers) { 
System.out.println(i);/*  Output in turn" 1 "," 2 "," 3 "," 4 "  */ 
} 

Listing 10: Using a loop variable of the same type as the element in Collection to be traversed


Collection< String> strings = new ArrayList< String>(); 
strings.add("A"); 
strings.add("B"); 
strings.add("C"); 
strings.add("D"); 
for (String str : integers) { 
System.out.println(str);/*  Output in turn" A "," B "," C "," D "  */ 
} 

The type of a loop variable can be the parent type of the element in the object to be traversed. For example, loop variables of type int are used to traverse an array of type byte[], and loop variables of type Object are used to traverse an array of type Collection < String > (All elements are String's Collection), etc.

Listing 11: Loop variable using the parent type of element in the object to be traversed


/*  To establish 1 a Collection */ 
String[] strings = {"A" .  "B" .  "C" .  "D"}; 
Collection stringList = java.util.Arrays.asList(strings); 
/*  To traverse the  */ 
for (Iterator itr = stringList.iterator(); itr.hasNext();) { 
Object str = itr.next(); 
System.out.println(str); 
} 
0

There can be an auto-converted relationship between the type of the loop variable and the type of the element in the object to be traversed. J2SE 1.5 includes an "Autoboxing/ ES209en-ES210en" mechanism that allows the compiler to automatically convert basic types to and from their wrapper classes (Wrapper Classes) if necessary. Therefore, use the loop variable of type Integer to traverse an array of type int[], or use the loop variable of type byte to traverse an array of type Collection < Byte > It's also possible.

Listing 12: Loop variable with a type that can be automatically converted with the type of the element in the object to be traversed


/*  To establish 1 a Collection */ 
String[] strings = {"A" .  "B" .  "C" .  "D"}; 
Collection stringList = java.util.Arrays.asList(strings); 
/*  To traverse the  */ 
for (Iterator itr = stringList.iterator(); itr.hasNext();) { 
Object str = itr.next(); 
System.out.println(str); 
} 
1

Note that the "type of element" mentioned here is determined by the object to be traversed. If it is an array of type Object[], then the type of element is Object, even if it contains all String objects.

Collection of the element type can be qualified

As of J2SE 1.4, it has been impossible to qualify the types of objects that can be held in Collection in the Java program, and they are all considered to be the most 1-like Object objects. 1 This problem was not resolved until J2SE 1.5, which introduced the "Generics" mechanism. Now you can use Collection < T > To indicate that all element types are T.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: