For-each Cycle
The For-each loop is also called an enhanced for loop, or a foreach loop.
The For-each loop is a new feature of JDK5.0 (other new features such as generics, auto-boxing, etc.).
The addition of the For-each loop simplifies the traversal of the collection.
Its syntax is as follows:
for (type Element:array)
{
SYSTEM.OUT.PRINTLN (Element);
}
Example
Its basic use can be directly read the code:
The code first compares two for loops, then implements a two-dimensional array with an enhanced for loop, and finally iterates through a list collection in three ways.
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
public class Foreachtest
{
public static void Main (string[] args)
{
Int[] arr = {1, 2, 3, 4, 5};
System.out.println ("----------old way Traversal------------");
Old Style
for (int i=0; i<arr.length; i++)
{
System.out.println (Arr[i]);
}
System.out.println ("---------New way to traverse-------------");
New style, enhanced for loop
for (int element:arr)
{
SYSTEM.OUT.PRINTLN (Element);
}
System.out.println ("---------traverse two-dimensional array-------------");
Traversing a 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 list in three different ways
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, using iterators
for (iterator<string> iter = List.iterator (); Iter.hasnext ();)
{
System.out.println (Iter.next ());
}
SYSTEM.OUT.PRINTLN ("----------mode 3-----------");
Third Way, use the enhanced for loop
for (String str:list)
{
System.out.println (str);
}
}
}
Disadvantages of the For-each loop: The index information is discarded.
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.
Java-enhanced for loop for each