From: http://blog.csdn.net/mcy478643968/archive/2009/05/17/4194543.aspx
Different from C #, foreach is a keyword in C #. in Java, the foreach statement is a special simplified version of the for statement, but the foreach statement cannot completely replace the for statement, any foreach statement can be rewritten to the for statement version.
The expression of the foreach statement in Java:
For (element type T element variable X: traversing object OBJ ){
References the Java Statement of X;
}
Example:
/**
* The foreach statement outputs a one-dimensional array.
*/
Public void test1 (){
// Define and initialize an array
Int arr [] = {2, 3, 1 };
System. Out. println ("---- 1 ----");
For (int x: ARR ){
System. Out. println (x); // outputs the values of array elements one by one.
}
Public void listtoarray (){
// Create a list and add elements
List <string> List = new arraylist <string> ();
List. Add ("1 ");
List. Add ("3 ");
// Use the froeach statement to output the set Element
System. Out. println ("---- 2 ----");
For (string X: List ){
System. Out. println (X );
}