Several usages analysis of Java for Loop _java

Source: Internet
Author: User

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 " traverse"-an element in an array or collection, it is generally implemented using a for loop (which, of course, is not possible with other kinds of loops). Just don't know because the word for is shorter, or because the meaning of the word for is the same as the operation, at which time the for loop is much more common than other loops.

For traversing an array, the loop typically takes this approach:

Listing 1: The traditional way to traverse an array

Copy Code code as follows:

/* Create an array */
int[] integers = {1, 2, 3, 4};
/* Start traversal */
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

Copy Code code as follows:

/* Create a collection * *
String[] strings = {"A", "B", "C", "D"};
Collection stringlist = java.util.Arrays.asList (strings);
/* Start traversal */
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

Copy Code code as follows:

/* Create an array */
int[] integers = {1, 2, 3, 4};

/* Start traversal */
for (int i:integers) {
System.out.println (i); /* In turn Output "1", "2", "3", "4" * *
}

The For loop used here is considered to be such a form during compilation:

Listing 4: Equivalent code for a simple way to traverse an array

Copy Code code as follows:

/* Create an array */
int[] integers = {1, 2, 3, 4};

/* Start traversal */
for (int variable name = 0; variable name armour < integers.length; variable name A + +) {
SYSTEM.OUT.PRINTLN (integers[variable name)); /* In turn Output "1", "2", "3", "4" * *
}

Here's " Variable name armour"is a name that is automatically generated by the compiler and does not cause confusion.

and traversing a collection operation can be used in this way:

Listing 5: A simple way to traverse collection

Copy Code code as follows:

/* Create a collection * *
String[] strings = {"A", "B", "C", "D"};
Collection list = java.util.Arrays.asList (strings);

/* Start traversal */
for (Object str:list) {
System.out.println (str); /* Output "A", "B", "C", "D" in turn
}

The For loop used here is considered to be such a form during compilation:

Listing 6: Equivalent code for a simple way to traverse collection

Copy Code code as follows:

/* Create a collection * *
String[] strings = {"A", "B", "C", "D"};
Collection stringlist = java.util.Arrays.asList (strings);

/* Start traversal */
For (iterator variable name B = List.iterator (); variable name B. Hasnext ();) {
Object str = variable name B. Next ();
System.out.println (str); /* Output "A", "B", "C", "D" in turn
}

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

Because the compiler for J2SE 1.5 will consider this form of a for loop as a corresponding traditional form during compilation, there is no need to worry about performance problems.

Without the "foreach" and "in" reasons

Java uses "for" (rather than a more explicit "foreach") to guide this loop, which is generally called the "For-each Loop," and uses ":" Instead of a more meaningful "in" To split the name of the loop variable and the object to be traversed. The main reason for this is to avoid compatibility problems because of the introduction of new keywords--In the Java language, the keyword is not allowed to be used as a variable name, although the use of the name "foreach" isnot very much, but "in" is a name that is often used to denote an input stream (for example, in the Java.lang.System class, there is a static property called "in" that represents the "standard input stream").

It is true that by using ingenious design syntax, keywords have special meanings in specific contexts to allow them to be used as regular identifiers. But the strategy, which complicates grammar, is not widely used.

A long history of the "For-each cycle"

The "For-each cycle" is not a recently emerged control structure. This control structure has been included in the 1979 officially released Bourne Shell (the first mature Unix command interpreter) (loops are guided with "for" and "in", and the loop body is identified with "do" and "done").

2. Prevent the circulation variable from being modified in the circulation body

By default, the compiler is allowed to reassign the loop variable in the loop body of the second for loop. However, it is generally not recommended because it has no effect on the outside of the loop and can easily cause difficulties in understanding the code.

Java provides a mechanism by which such operations can be blocked during compilation. The concrete approach is to precede the loop variable type with a "final" modifier. Thus, assigning a loop variable in the loop body results in a compilation error. With this mechanism, it is possible to effectively prevent the intentional or unintentional " modification of the loop variable in the circulation body" operation.

Listing 7: Prohibit re-assignment

Copy Code code as follows:

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

Note that this only disables the redistribution of the loop variable. It is not prohibited to assign values to the properties of a loop variable, or to invoke a method that allows the contents of a loop variable to change.

Listing 8: Allow modification status

Copy Code code as follows:

random[] randoms = new Random[]{new Random (1), New Random (2), New Random (3)};
For (final Random r:randoms) {
R.setseed (4); /* Set all random objects to use the same seed * *
System.out.println (R.nextlong ()); /* seed is the same, the first result is the same * *
}

3. Type compatibility issues

In order to ensure that the cyclic variable can be safely assigned at the beginning of each cycle, J2SE 1.5 has certain limitations on the type of the loop variable. Under these restrictions, the type of the loop variable can have some choices:

The type of the loop variable can be the same type as the element in the object to be traversed. For example, an int-type loop variable is used to traverse a int[-type array, and an object-type loop variable is used to traverse a collection.

Listing 9: The same type of loop variable used and the element in the array to be traversed

Copy Code code as follows:

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

Listing 10: The same type of loop variable used and the element in the 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 "A", "B", "C", "D" in turn
}

The type of a loop variable can be the ancestor type of the element in the object to be traversed. For example, an int-type loop variable is used to traverse a byte[-type array, and an object-type loop variable is used to traverse a collection< string> (all elements are String collection).

Listing 11: A loop variable that uses the ancestor 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.out.println (str);/* output "A", "B", "C", "D" in turn
}

The type of the loop variable can have a relationship that can be automatically converted between the types of elements in the object being traversed. The J2SE 1.5 contains the "autoboxing/auto-unboxing" mechanism, allowing the compiler to automatically convert between the base type and their parcel class (wrapper Classes) when necessary. Therefore, it is also possible to traverse an array of int[by an integer loop variable, or to traverse a collection< byte> using a Byte-type loop variable.

Listing 12: Loop variables for types that are automatically converted using the type of elements in the object to be traversed
int[] integers = {1, 2, 3, 4};
for (Integer i:integers) {
System.out.println (i); /* In turn Output "1", "2", "3", "4" * *
}

Note that the "type of element" Here is determined by the object to be traversed-if it is an array of object[, then the type of the element is object, even if it contains a string object.

collection that can qualify element types

By the end of J2SE 1.4, the types of objects that can be stored in collection are never qualified in Java programs-they are all considered the most common object objects. Up to J2SE 1.5, the problem was solved after the introduction of the "Generics (generics)" mechanism. You can now use collection< t> to indicate that all element types are collection of T.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.