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.
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); } }}
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.
Enhanced for Loop