Quote: https://www.cnblogs.com/mengdd/archive/2013/01/21/2870019.html
For-Each loop
For-Each loop, also known as the enhanced for loop, or call foreach loop.
For-Each cycle is a new feature of JDK5.0 (Other new features such as generics, automatic packing, etc.).
For-Each cycle was added simplified set of traversal.
The syntax is as follows:
for(type element: array)
{
System.out.println(element);
}
example
Which may be used in substantially directly look at the code:
First comparison code for two cycles; loop through the realization of a two-dimensional array for reinforcement; last three ways to traverse a set of List.
java.util.ArrayList import;
java.util.Iterator import;
import java.util.List;
ForeachTest class public
{
public static void main (String [] args)
{
int [] = {ARR. 1, 2,. 3,. 4,. 5};
System.out.println ( "old ---------- ------------ traverse a ");
// old way
for (int I = 0; I <arr.length; I ++)
{
System.out.println (ARR [I]);
}
System.out.println ( "--------- ------------- new ways to traverse");
// new wording, enhanced for loop
for (int element: arr )
{
System.out.println (Element);
}
System.out.println ( "two-dimensional array traversal ------------- ---------");
// traversing the two-dimensional array
int [] [] = {{arr2 is. 1, 2,. 3}, {. 4,. 5,. 6}, {. 7,. 8,. 9}};
for (int [] Row: arr2 is)
{
for (int Element: Row)
{
System.out.println (Element);
}
}
// in three ways through the collection List
List <String> = new new List the ArrayList <String> ();
List.add ( "A");
List.add ( "B");
List.add ( "C" );
System.out.println ( "---------- embodiment 1-----------");
// first mode, for normal loop
for (int i = 0; I <list.size (); I ++)
{
System.out.println (List.get (I));
}
System.out.println ( "mode 2 --- ---------- -------- ");
// second embodiment, using an iterator
for (the iterator <String> = list.iterator ITER (); iter.hasNext ();)
{
System.out.println (ITER .next ());
}
System.out.println ( "---------- embodiment 3-----------");
// third way, enhanced the for loop
for (String str:list)
{
System.out.println(str);
}
}
}
For-Each loop drawback: the index lost information.
When traversing collection or array, if you need access to a collection or array subscript, it is best to use the old-fashioned way to achieve the cycle or traverse, rather than enhanced for loop, because it is missing the index information.