Several usage analyses of the Java for loop

  • 2020-04-01 01:44:19
  • OfStack

J2SE 1.5 provides another form of a for loop. This form of a for loop makes it easier to iterate over objects of types such as groups and collections. This article shows you how to use this loop, how to define classes that can be traversed this way, and explains some common problems with this mechanism.

In Java programs, to "execute" � � or "through" � � an array or a Collection of elements, typically using a for loop to achieve (of course, also with other kinds of circulation is not can't, just don't know because of the word for the length of the short, or because the for the meaning of the word and compare with the operation, when the for loop is much more common than other circulation).

For traversal groups, the loop is generally written like this:

Listing 1: the traditional way of traversing groups


 
 int[] integers = {1 .  2 .  3 .  4};
 
 for (int j = 0; j < integers.length; j++) {
     int i = integers[j];
     System.out.println(i);
 } 

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

Listing 2: the traditional way of traversing a Collection object



 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);
 }

Another form of for loop is introduced in J2SE 1.5, the latest version of the Java language. With this form of the for loop, you can now do the traversal in a much simpler way.

  1. The second for loop

Loosely speaking, Java's second for loop basically looks like this:

  For (loop variable type loop variable name: the object to be traversed) & PI; The loop body

With this syntax, traversing an array can be written like this:

Listing 3: a simple way to iterate through groups


 
 int[] integers = {1 .  2 .  3 .  4};

 
 for (int i : integers) {
     System.out.println(i); 
 }

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


 
 int[] integers = {1 .  2 .  3 .  4};

 
 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 ]); 
 }

The "variable name a" here is a name that is automatically generated by the compiler without causing confusion.

Operations traversing a Collection can be written as follows:

Listing 5: a simple way to traverse a Collection


 
 String[] strings = {"A" .  "B" .  "C" .  "D"};
 Collection list = java.util.Arrays.asList(strings);

 
 for (Object str : list) {
     System.out.println(str); 
 }

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

Listing 6: equivalent code for a simple way to iterate through a Collection


 
 String[] strings = {"A" .  "B" .  "C" .  "D"};
 Collection stringList = java.util.Arrays.asList(strings);

 
 for (Iterator  The variable name b  = list.iterator();  The variable name b .hasNext();) {
     Object str =  The variable name b .next();
     System.out.println(str); 
 }

Here "variable name b" is also a name that is automatically generated by the compiler without causing confusion.

Because at compile time, the J2SE 1.5 compiler sees this form of the for loop as its traditional counterpart, there are no performance issues to worry about.

No "foreach" and "in" reasons

Java USES "for" (instead of the more explicit "foreach") to guide this loop, which is commonly called "for-each loop", and ":" (instead of the more explicit "in") to separate the loop variable name from 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 the Java language, not allowed to use keywords as a variable name, although the use of the name "foreach" is not very much, but the "in" is a frequently used to represent the name of the input stream (such as Java. Lang. The System class, there is a name called the "in" the static properties, said "the standard input stream").

It is certainly possible to use a clever design syntax that allows keywords to have special meanings only in specific contexts, allowing them to be used as common identifiers as well. However, this strategy, which can complicate the syntax, has not been widely adopted.

  The "for-each cycle" has a long history

The for-each loop is not a recent control structure. This control structure was included in the Bourne shell (the first full-blown UNIX command interpreter), which was released in 1979 (the loop was booted with "for" and "in", and the loop body was identified with "do" and "done").

2. Prevent the modification of loop variables in the loop body

By default, the compiler allows reassigned loop variables in the body of the second for loop. However, this practice is generally not recommended because it has no effect on the outside of the circulation and can cause difficulties in understanding the code.

Java provides a mechanism to block such operations at compile time. This is done by prefixing the loop variable type with a "final" modifier. Thus, assigning values to loop variables in the body of the loop results in a compilation error. With this mechanism, you can effectively eliminate the operation of "modifying the loop variables in the loop body" intentionally or unintentionally.

Listing 7: reassigning is not allowed


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

Note that this simply prohibits reassigning loop variables. It is not forbidden to assign values to properties of a loop variable, or to call methods that change the contents of the loop variable.

Listing 8: allow state changes


 Random[] randoms = new Random[]{new Random(1) .  new Random(2) .  new Random(3)};
 for (final Random r : randoms) {
     r.setSeed(4); 
     System.out.println(r.nextLong()); 
 }

3. Type compatibility problem

In order to ensure that loop variables are securely assigned at the beginning of each loop, J2SE 1.5 places certain restrictions on the type of loop variables. Under these restrictions, the types of loop variables 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, an int[] array is traversed by an int loop, a Collection is traversed by an Object loop, and so on.

Listing 9: using loop variables of the same type as the elements in the array to be traversed


 int[] integers = {1 .  2 .  3 .  4};
 for (int i : integers) {
     System.out.println(i); 
 }

Listing 10: using loop variables of the same type as the elements in the Collection to be traversed
  Collection< String> Strings = new ArrayList< String> (a);
  Strings. The add (" A ");
  Strings. The add (" B ");
  Strings. The add (" C ");
  Strings. The add (" D ");
  Int (String STR: integers) {
        System. The out. Println (STR);
  }

The type of the loop variable can be the parent type of the element in the object to be traversed. For example, a byte[] array is iterated with an int loop, and a Collection< array is iterated with an Object loop. String> (all elements are a Collection of strings), etc.

Listing 11: loop variables using the parent type of the element in the object to be traversed
  String[] strings = {"A", "B", "C", "D"};
  Collection< String> List = Java. Util. Arrays. AsList (strings).
  For (Object STR: list) {
        System. The out. Println (STR);
  }

There can be an automatic conversion 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/ auto-unboxing" mechanism that allows the compiler to automatically convert between basic types and their Wrapper Classes if necessary. Thus, an int[] array is iterated with an Integer loop, or a Collection< array is iterated with a byte loop. Byte> Is also feasible.

Listing 12: loop variables with types that can be automatically converted with the types of elements in the object to be traversed
  Int [] integers = {1, 2, 3, 4};
  For (Integer I: integers) {
        System. The out. Println (I);
  }

Note that the "type of element" 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 String objects.

You can qualify a Collection of element types

As of J2SE 1.4, it has never been possible in a Java program to qualify the types of objects that can be stored in a Collection, and they are all considered to be the most general of objects. This issue was not resolved until J2SE 1.5, when the "Generics" mechanism was introduced. Collection< T> To indicate that all element types are collections of T.


Related articles: