Starting from JDK1.5, new features Foreach has been added. It is a short form of FOR looping data. The keywords used are still for, but the parameter format is different. Its detailed usage is:
For (Type E: Collection) {// Use of variable E}
Parameter description:
E: Its type Type is a type of element value in a collection or array. This parameter is a element in the collection or array.
Collections: The collection or array to be traversed can also be iterators.
Use parameter E in the cycle, this parameter is the elemental value obtained from the collection or array and the iterative device, and the elemental value is traversed from beginning to end.
Specific examples:
// You must import the two packs 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> (); // Create list collection list.add ("ABC"); // Initialize list collection list.add ("def"); list.add ("gHi"); list.add ( "jkl"); list.add ("mno"); list.add ("PQR"); System.out.print ("Foreach traversed: /n /t"); for (string string: list) { / / /Traversing the list collection system.out.print (string); // Output the elemental value of the output collection} system.out.println (); string [] strs = new string [list.size ()]; list.toarray (strs) ; // Create an array System.out.println ("Foreach traversed array:/n/t"); for (string string: strs) {// traversing array System.out.print (string); // Output array elemental value value }}}
Summarize:
The previous version of the JDK uses for the collection, array and iterations to traverse, which requires creating index variables and conditional expressions. These will cause the code to confuse and increase the chance of errors. And in each cycle, the index variable or iterator will appear 3 times, with two chances to make mistakes. And there will be some performance losses, and its performance is slightly behind the Foreach cycle. Therefore, for the traversal of the data set, it is recommended to use the Foreach cycle.