When such a loop is used, you do not need to judge the length of the array first. Then, you can only traverse the elements in the array and cannot modify the elements in the array.
Package com. Test. for_each;
Import java. util. arraylist;
Import java. util. iterator;
Import java. util. List;
Public class fortest
{
Public static void main (string ARGs [])
{
Int arr [] = {1, 2, 3, 4, 5, 6, 7, 8 };
/**
* New Writing Method
*/
For (int A: ARR)
System. Out. println ();
/**
* Old-style Writing
*/
For (INT I = 0; I <arr. length; I ++)
System. Out. println (ARR [I]);
String arr2 [] = {"good", "stream", "Oh ","!! "};
For (string A2: arr2)
System. Out. println (A2 );
Int arr3 [] [] = {, 3}, {, 6, },{, 9 }};
For (INT A31 []: arr3)
{
For (INT A32: A31)
{
System. Out. println (A32 );
}
System. Out. println ();
}
List <string> List = new arraylist <string> ();
List. Add ("good ");
List. Add ("stream ");
List. Add ("oh ");
List. Add ("!! ");
/**
* Traversal based on the Collection class Length
*/
For (INT I = 0; I <list. Size (); I ++)
{
System. Out. println (list. Get (I ));
}
/**
* Traverse by iterator
*/
For (iterator I = List. iterator (); I. hasnext ();)
{
System. Out. println (I. Next ());
}
/**
* Based on the New for-each Traversal
*/
For (string element: List)
System. Out. println (element );
}
}