From JDK1.5, added a new feature foreach, which is a shorthand form for looping through data, using a keyword that is still for, but with a different parameter format. Its detailed usage is:
for (Type e:collection) {
Parameter description:
E: Its type is the type of the element value in the collection or array, which is an element of the collection or array collection.
Collections: A collection or array to traverse, or an iterator.
The parameter e is used in the loop body, which is the element value that foreach obtains from the collection or array and the iterator, and the element values are traversed from start to finish.
Specific examples:
You must import the two packages below util: arraylist,list;
Import java.util.ArrayList;
Import java.util.List;
public class Foreach {public
static void Main (string[] arg) {
list<string> List = new ARRAYLIST<STRING&G t; (); Create a list collection
List.add ("abc");//Initialize the list collection
list.add ("def");
List.add ("Ghi");
List.add ("JKL");
List.add ("MnO");
List.add ("PQR");
System.out.print ("foreach Traversal set: \n\t");
for (string string:list) { //Traverse List collection
System.out.print (string); The element value of the output set
}
System.out.println ();
string[] STRs = new string[list.size ()];
List.toarray (STRs); Creates an array
System.out.println ("foreach Traversal array: \n\t");
for (string string:strs) { //traversal array
System.out.print (string); Output array element value
}
}
Summarize:
The previous version of the JDK uses a for loop to traverse the collection, array, and iterator, which requires creating index variables, conditional expressions, which can cause code confusion and increase the likelihood of errors. And in each loop, the index variable or iterator appears 3 times, with two chance of error. And there are some performance losses, and their performance is slightly behind the Foreach loop. Therefore, it is recommended that you use a Foreach loop for traversing data sets.