First, the Foreach Loop statement describes:
1. Format:
For (type variable name: traversed array or collection) {
Other operations (output operations)
}
2. Function:
Mainly used to simplify the writing
Second, the Foreach Loop statement iterates through the array:
public class Onehundredandeight_onehundredandnine { public static void main (string[] args) {string[] names = {"Meng Meng", "pure pure", "Love Love", "Phoenix Phoenix", "Dream Dream" for (String x:names) {System.ou T.print (x + "" ); } }}
Public class Foreachdemo { publicstaticvoid main (string[] args) { int [] arr = {3,5,6,7}; for (int i:arr) { System.out.println (i); }}}
Third, the Foreach Loop statement iterates through the collection
The list collection is available in two ways, an iterator, and a for loop, using the Get () method to take the elements out of the corner
Only one way to remove a set set is an iterator
Any collection that supports iterators can use the advanced for
Iterate over a collection to get only the elements, but not too many operations on the collection
Iterators can also remove elements from a collection in addition to traversal
If it is a listiterator, you can also perform the action of adding and checking the collection during the traversal.
Importjava.util.ArrayList; Public classForeachdemo { Public Static voidMain (string[] args) {ArrayList<String> Al =NewArraylist<string>(); Al.add ("ABC2"); Al.add ("ABC3"); Al.add ("ABC1"); /*For (iterator<string> it = Al.iterator (); It.hasnext ();) {System.out.println (It.next ()); } */ for(String s:al) {//s = "KK";//s does not change the elements in the collection, only the elements in the collection can be removed, not modify the actionSystem.out.println (s); } System.out.println (AL);//The result is still the original set }}
Iv. differences between traditional for and advanced for:
1. Legacy for: You can perform many times on a statement because you can define the control loop increment and condition
2, the advanced for has a limitation, must have the target to be traversed, and may produce a lot of garbage, in some memory more intense projects are not recommended, such as in the Android program, it is recommended to use the traditional for when traversing the array, because the traditional for can use the corner
3, advanced for can only traverse the singleton collection, to the variable double-column collection (such as the map collection), you can change the map collection into a singleton collection and then use the advanced for
ImportJava.util.HashMap; Public classForeachdemo { Public Static voidMain (string[] args) {HashMap<Integer,String> HM =NewHashmap<integer,string>(); Hm.put (1, "a"); Hm.put (2, "a"); Hm.put (3, "a"); //Use the keyset or EntrySet method first to change to set set, using the Advanced for for(Integer key:hm.keySet ()) {String value=Hm.get (key); SYSTEM.OUT.PRINTLN (Key+"...."+value); } }}
Foreach Loop statement