Java foreach uses

Source: Internet
Author: User
Tags arrays
Summary of Use of foreach statementThe foreach statement is one of the new features of Java5, and foreach provides a great convenience for developers in traversing arrays and collections. The foreach statement is a special, simplified version of the for statement, but the foreach statement does not completely replace the For statement, however, any foreach statement can be rewritten as a for statement version. foreach is not a keyword, and it is customary to refer to this special for statement format as a "foreach" statement. From the literal meaning of the word foreach is "for each" meaning. That's actually what it means. foreach statement format: for (element type T element variable x: Traversal object obj) {References x's Java statement;} Here's a simple example of two examples to see how foreach simplifies programming. The code is as follows: A. Foreach simplifies the traversal of arrays and collectionsImport Java.util.Arrays;
Import java.util.List;
Import java.util.ArrayList;

/**
* Created by IntelliJ idea.
* User:leizhimin
* date:2007-12-3
* time:16:58:24
* Summary of the use of the foreach statement for Java5 new features
*/
public class Testarray {
public static void Main (String args[]) {
Testarray test = new Testarray ();
Test.test1 ();
Test.listtoarray ();
Test.testarray3 ();

}

/**
* The foreach statement outputs a one-dimensional array
*/
public void Test1 () {
Define and initialize an array
int arr[] = {2, 3, 1};
SYSTEM.OUT.PRINTLN ("----1----one-dimensional array before sorting");
for (int x:arr) {
SYSTEM.OUT.PRINTLN (x); Output the value of an array element individually
}

sorting arrays
Arrays.sort (arr);

Use Java new features for Each loop output array
SYSTEM.OUT.PRINTLN ("----1----ordered one-dimensional array");
for (int x:arr) {
SYSTEM.OUT.PRINTLN (x); Output the value of an array element individually
}
}

/**
* The collection is converted to a one-dimensional array
*/
public void Listtoarray () {
Create a list and add elements
list<string> list = new arraylist<string> ();
List.add ("1");
List.add ("3");
List.add ("4");

To output a collection element with a Froeach statement
SYSTEM.OUT.PRINTLN ("----2----froeach statement output set element");
for (String x:list) {
SYSTEM.OUT.PRINTLN (x);
}

Convert ArrayList to an array
Object s[] = List.toarray ();

To output a collection element with a Froeach statement
SYSTEM.OUT.PRINTLN ("----2----an array element converted from a set of Froeach statement output");
for (Object x:s) {
System.out.println (X.tostring ()); Output the value of an array element individually
}
}

/**
* foreach output two dimensional array test
*/
public void TestArray2 () {
int arr2[][] = {4, 3}, {1, 2}};
SYSTEM.OUT.PRINTLN ("----3----foreach output two-dimensional array test");
for (int x[]: arr2) {
for (int e:x) {
System.out.println (e); Output the value of an array element individually
}
}
}

/**
* foreach output three-dimensional array
*/
public void TestArray3 () {
int arr[][][] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};

SYSTEM.OUT.PRINTLN ("----4----foreach output three-dimensional array test");
For (int[][] a2:arr) {
For (int[] a1:a2) {
for (int x:a1) {
SYSTEM.OUT.PRINTLN (x);
}
}
}
}
Run Result:----1----One-dimensional array before sorting
2
3
1
----1----Sorted one-dimensional array
1
2
3
----2----Froeach Statement output collection elements
1
3
4
----2----An array element converted from the Froeach statement output collection
1
3
4
----4----foreach output three-dimensional array test
1
2
3
4
5
6
7
8

Process finished with exit code 0 Ii. Limitations of the foreach statementAs you can see from the example above, if you want to refer to an array or an index of a collection, the foreach statement is not possible, and foreach simply passes through the enumeration group or collection. Here's an example to see:/**
* Created by IntelliJ idea.
* User:leizhimin
* date:2007-12-3
* TIME:17:07:30
* The limitations of the foreach statement
*/
public class TestArray2 {

public static void Main (String args[]) {
Define a one-dimensional array
int arr[] = new INT[4];
SYSTEM.OUT.PRINTLN ("Output just defined array----" before----unassigned);
for (int x:arr) {
SYSTEM.OUT.PRINTLN (x);
}

Assigning values to an array element by index
SYSTEM.OUT.PRINTLN ("----Assign a value to an array element through a loop variable----");
for (int i = 3; i > 0; i--) {
Arr[i] = i;
}
Array created by looping output
SYSTEM.OUT.PRINTLN ("----assignment, the foreach output creates a good array----");
for (int x:arr) {
SYSTEM.OUT.PRINTLN (x);
}
}
}
Run Result: Outputs the array just defined before----unassigned----
0
0
0
0
----Assign values to an array element through a loop variable----
----assignment, the foreach output creates a good array----
0
1
2
3

Process finished with exit code 0 Third, summary

The

foreach statement is an enhanced version of the For statement in particular, simplifying programming and improving the readability and security of your code (not to be afraid of array bounds). Relatively old for statement is a good supplement. Advocate a place where you can use foreach and stop using for. In the case of a collection or an array index, foreach seems powerless, and this is the time to use a for statement. foreach is generally used in conjunction with generics.

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.