Summary of Java foreach statement usage

Source: Internet
Author: User

The foreach statement is one of the new features of Java5, and foreach provides developers with great convenience 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 version of the for statement. foreach is not a keyword, and it is customary to call this special for-statement format a "foreach" statement. To understand the meaning of foreach as "for each" from the literal meaning of English. That's actually what this means. foreach statement format: for (element type T element variable x: Traversal object obj) {reference x 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 collections

Import 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 * JAVA5 new features foreach statement use summary */public class Testarray {public Stati         c void Main (String args[]) {testarray test = new Testarray ();         Test.test1 ();         Test.listtoarray ();     Test.testarray3 ();         /** * foreach statement output one-dimensional array */public void test1 () {//define and initialize an array of 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 the array element individually}//Sort the Arrays Arrays.sort (arr);         Using the new Java feature for Each loop output array System.out.println ("----1----one-dimensional array after sorting"); for (int x:arr) {System.out.println (x);//Output The value of the array element individually}}/** * Collection converted to a one-dimensional array */P ublic void Listtoarray () {//Create list and add element list<string> list = new Arraylist<string>();         List.add ("1");         List.add ("3");         List.add ("4");         Use the Froeach statement to output the collection element System.out.println ("----2----froeach statement output set element");         for (String x:list) {System.out.println (x);         }//Convert ArrayList to an array of Object s[] = List.toarray ();         Use the Froeach statement to output the collection element System.out.println ("----2----The Froeach statement output set of the array elements converted from the"); for (Object x:s) {System.out.println (x.tostring ());//Output The value of the 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 the 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.O                 UT.PRINTLN (x); }             }         }     } }

Run Result:----1----One-dimensional array before sorting
2
3
1
----1----One-dimensional array after sorting
1
2
3
----2----Froeach Statement Output collection element
1
3
4
----2----An array element that is converted from a 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 0Ii. Limitations of the foreach statementThe above example shows that if you want to reference an array or an index of a collection, the foreach statement cannot do it, and foreach simply faithfully passes through the group or the collection. Let's take a look at the following example:
/** * Created by IntelliJ idea. * User:leizhimin * date:2007-12-3 * time:17:07:30 * Limitations of the foreach statement */public class TestArray2 {public     static void M Ain (String args[]) {         //define a one-dimensional array         int arr[] = new Int[4];         SYSTEM.OUT.PRINTLN ("Output of the array just defined before----is unassigned----");         for (int x:arr) {             System.out.println (x);         }         Assigns a value to an array element by index         SYSTEM.OUT.PRINTLN ("----assigns a value to an array element through a loop variable----");         for (int i = 3; i > 0; i--) {             arr[i] = i;         }         The loop output creates an array of         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 a value to an array element through a loop variable----
After----assignment, the foreach output creates a good array----
0
1
2
3

Process finished with exit code 0Iii. SummaryThe foreach statement is an enhanced version of the For statement in particular cases, simplifying programming, and improving the readability and security of the code (without fear of arrays being out of bounds). This is a good addition to the old for statement. If you want to use foreach, don't use for anymore. In the case of a set or array index, foreach appears to be powerless, and this is the time to use a for statement.above from "Lava"blog, be sure to keep this sourcehttp://lavasoft.blog.51cto.com/62575/53321


Example: Compare two for loops, then implement a two-dimensional array with an enhanced for loop, and finally traverse a list collection in three ways.

Import Java.util.arraylist;import Java.util.iterator;import Java.util.list;public class foreachtest{public static Voi                D main (string[] args) {int[] arr = {1, 2, 3, 4, 5};        System.out.println ("----------old way Traversal------------");        Legacy mode for (int i=0; i<arr.length; i++) {System.out.println (arr[i]);                } System.out.println ("---------New way to traverse-------------");        New notation, enhanced for loop for (int element:arr) {System.out.println (element);                } System.out.println ("---------traverse two-dimensional array-------------");                Traverse the two-dimensional array int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};            For (int[] row:arr2) {for (int element:row) {System.out.println (element); }}//Iterate through the collection in three ways list list<string> list = new Arraylist<string> (                ); List.add ("a");        List.add ("B");                List.add ("C");        SYSTEM.OUT.PRINTLN ("----------mode 1-----------");                    The first way, the normal for loop for (int i = 0; i < list.size (); i++) {System.out.println (List.get (i));        } System.out.println ("----------mode 2-----------");        The second way, use the iterator for (iterator<string> iter = List.iterator (); Iter.hasnext ();)        {System.out.println (Iter.next ());        } System.out.println ("----------mode 3-----------");                    The third way, use the enhanced for loop for (String str:list) {System.out.println (str); }    }}

Thus, the disadvantage of the For-each loop is that it loses the index information.

When traversing a collection or array, if you need to access the index of a collection or array, it is best to use the old-fashioned way to loop or traverse, rather than using an enhanced for loop, because it loses subscript information.  

Reference: Java foreach implementation principle http://blog.csdn.net/a596620989/article/details/6930479Java about for and foreach, both efficiency and security http://flyvszhb.iteye.com/blog/2163569


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Summary of Java foreach statement usage

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.