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 the JDK5.0 (other new features such as generics, automatic boxing, etc.).
The addition of the For-each loop simplifies the traversal of the set.
The syntax is as follows:
for (type Element:array)
{
System.out.println (element);
}
Example
Its basic use can look directly at the code:
Two for loops are first compared in the code, then the two-dimensional array is traversed with an enhanced for loop, and a list collection is traversed in three different 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 to traverse------------");
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 ("---------traversing two-dimensional array-------------");
Traversal 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);
Three ways to traverse the collection list list<string> list = new arraylist<string> ();
List.add ("a");
List.add ("B");
List.add ("C");
System.out.println ("----------Way 1-----------");
The first way, the general for loopfor (int i = 0; i < list.size (); i++) {System.out.println (List.get (i));
} System.out.println ("----------mode 2-----------");
The second way is to use an iterator for (iterator<string> iter = List.iterator (); Iter.hasnext ();)
{System.out.println (Iter.next ());
} System.out.println ("----------mode 3-----------");
The third way is to use the enhanced for loop for (String str:list) {System.out.println (str); }
}
}
Disadvantages of For-each Loops: Lost index information.
When traversing a collection or array, if you need to access the index of the collection or array, it is best to use the old-fashioned way to implement loops or traversal rather than using an enhanced for loop because it loses subscript information.
The above is a small series for everyone to talk about the Java-enhanced for loop for all the contents of each, I hope to help you, a lot of support cloud Habitat Community ~