Several ways to do Java for loops

Source: Internet
Author: User

J2SE 1.5 provides another form of a for loop. With this form of for loop, you can iterate over objects of types 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 like this, and explain some common issues with this mechanism.

In a Java program, to "process"-or, "traverse"-an array or an element in a collection, it is generally implemented with a for loop (of course, it is not possible to use other kinds of loops, but it is not known because the length of the word for is shorter, Or because the meaning of the word for is compared with this kind of operation, at this time the for loop is much more common than other loops.

For iterating over an array, this loop is generally written like this:

Listing 1: The traditional way to iterate through an array

/* 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);

}

For the traversal of the collection object, this loop is usually taken in this form:

Listing 2: The traditional way to traverse a collection object

/* Build 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 has been introduced. With this form of a for loop, it is now possible to traverse the work in a simpler way.

1. Second for loop

Not strictly speaking, the second type of Java for loop is basically this 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: An easy way to iterate through an array

/* Create an array */

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

/* Start traversal */

for (int i:integers) {

System.out.println (i);/* output "1", "2", "3", "4" in turn */

}

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

Listing 4: Equivalent code for an easy way to iterate through an array

/* Create an array */

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

/* Start traversal */

for (int variable name = 0; variable name <integers.length; variable name + +) = "" {

SYSTEM.OUT.PRINTLN (integers[variable name);/* output "1", "2", "3", "4"/*

}

The "variable name" is a name that is generated automatically by the compiler and does not cause confusion.

This can be done by traversing a collection operation:

Listing 5: A simple way to traverse collection

/* Build 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 the form during compilation:

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

/* Build 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 and does not cause confusion.

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

Reasons for not using "foreach" and "in"

Java uses "for" (rather than more meaningful "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 the problem of compatibility due to the introduction of new keywords-in the Java language, it is not allowed to use the keyword as a variable name, although the use of the name "foreach" is not very much, but "in" is a name that is often used to represent the input stream (for example, in the Java.lang.System class, there is a static property called "in" that represents "standard input stream").

It is true that the clever design syntax allows the keywords to have special meanings only in specific contexts, allowing them to be used as normal identifiers. But this strategy, which complicates the syntax, has not been widely adopted.

A long history of the "For-each cycle"

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

2. Prevent modification of cyclic variables in the loop body

By default, the compiler is allowed to re-assign a loop variable to the loop body of the second for loop. However, since this practice has no effect on the outside of the loop, and it is easy to create difficulties in understanding the code, it is generally not recommended.

Java provides a mechanism to block such operations during compilation. The specific method is to precede the loop variable type with a "final" modifier. In this way, the loop variable is assigned in the loop body, resulting in a compilation error. With this mechanism, it is possible to effectively eliminate intentional or unintentional "modification of cyclic variables in the loop body" operation.

Listing 7: Disallow re-assignment

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

for (final int i:integers) {

i = I/2; /* ERROR at compile time */

}

Note that this only disables the re-assignment of the loop variable. Assigning a value to a property of a loop variable, or invoking a method that allows the contents of a loop variable to change, is not forbidden.

Listing 8: Allow modification of State

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 Same, the first result is the same */

}

3. Type compatibility issues

To ensure that the loop 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 choice:

The type of the loop variable can be the same as the type of the element in the object to be traversed. For example, iterate over an array of type int[by using the INT loop variable to iterate over a collection with the type of the object's loop variable.

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

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

for (int i:integers) {

System.out.println (i);/* output "1", "2", "3", "4" in turn */

}

Listing 10: Using the same type of loop variable as 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 the loop variable can be the ancestor type of the element in the object to be traversed. For example, iterate over an array of type byte[by using the INT loop variable to traverse a collection< string> (all elements are String collection), and so on.

Listing 11: Loop variable using 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 to be traversed. J2SE 1.5 contains a mechanism for "autoboxing/auto-unboxing" that allows the compiler to automatically convert between basic types and their package classes (Wrapper Classes) when necessary. Therefore, it is possible to traverse an array of type int[] with an integer loop variable, or to traverse a collection< byte> with a Byte-type loop variable.

Listing 12: Looping variables for types that are automatically converted with the types of elements in the object to be traversed

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

for (Integer i:integers) {

System.out.println (i);/* output "1", "2", "3", "4" in turn */

}

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

collection that can qualify element types

As of J2SE 1.4, there is always no way to limit the types of objects that can be saved in a Java program-they are all considered to be the most generic object objects in the collection. Until J2SE 1.5, the "Generics (generics)" mechanism was introduced, and the problem was solved. It is now possible to use collection< t> to indicate that all element types are collection of T.

This article is purely for reference, such as invasion of the deletion.

Several ways to do Java for loops

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.