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);
}
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.
Importjava.util.ArrayList;Importjava.util.Iterator;Importjava.util.List; public classforeachtest{ public Static voidmain (string[] Args) {int[] arr = {1, 2, 3, 4, 5}; System.out.println ("traverse----------------------old way"); //Old Style for(inti=0; i<arr.length; i++) {System.out.println (arr[i]); } System.out.println ("---------new Way to traverse-------------"); //new style, enhanced for loop for(intElement:arr) {System.out.println (element); } System.out.println ("---------traverse a two-dimensional array-------------"); //traversing a two-dimensional array int[] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} ; for(int[] Row:arr2) { for(intElement:row) {System.out.println (element); } } //iterate through the collection list in three different waysList<String> list =NewArraylist<string>(); List.add (A); List.add ("b"); List.add (C); System.out.println ("----------way 1-----------"); //the first way, the normal for loop for(inti = 0; I < list.size (); i++) {System.out.println (list.get (i)); } System.out.println ("----------way 2-----------"); //the second way, using iterators for(iterator<string> iter =list.iterator (); Iter.hasnext ();) {System.out.println (iter.next ()); } System.out.println ("----------way 3-----------"); //Third way, Use the enhanced for loop for(String Str:list) {System.out.println (str); } }}
Java-enhanced for loop for each