Enhanced for loop.
After checking on the Internet, the enhanced for loop is a new feature of java1.5. The so-called "enhanced for loop" mainly targets containers. When this feature is used, developers can hand over the logic of "traversing containers with iterator" to the compiler for processing.
For example, an old example:
String name [] = {"Zhang San", "Li Si", "Wang Wu "};
For (INT I = 0; I <name. length; I ++ ){
System. Out. println (name [I]);
}
The enhanced for loop can be written as follows:
String name [] = {"Zhang San", "Li Si", "Wang Wu "};
For (string STR: Name ){
System. Out. println (STR );
}
You can also traverse a two-dimensional array. Write the following statement:
String name [] [] = {"Zhang San", "Li Si", "Wang Wu" },{ "ZHANG Liu", "Li Qi", "Wang ba "}, {"Zhang JIU", "Li Shi", "Wang Xi "}};
For (string str1: Name ){
For (string str2: str1 ){
System. Out. println (str2 );
}
}
In fact, this feature should be generally combined with generics for the greatest benefit. Let's see how we used to traverse the collection class. A simple example:
Arraylist <string> arraylist = arraylist <string> ();
For (INT I = 0; I <10; I ++ ){
Arraylist. Add ("mybook" + I );
}
For (INT I = 0; I <arraylist. Size (); I ++ ){
System. Out. println (arraylist [I]);
}
After using the enhanced for loop, you can write it like this (similar to the above ):
Arraylist <string> arraylist = arraylist <string> ();
For (INT I = 0; I <10; I ++ ){
Arraylist. Add ("mybook" + I );
}
For (string STR: arraylist )[
System. Out. println (STR );
}
----- Transferred from Sina Blog