Enhanced for Loop:
Format: for (variable data type variables to traverse: The Array (collection) name where the element resides)
Also known as for (Type Element:array or collection)
To iterate through a collection using foreach:
Only the elements in the collection can be obtained, and the collection cannot be manipulated.
The iterator iterator, in addition to being traversed, can also remove the elements in the collection as they traverse.
If you are using Listiterator, you can also perform the actions of adding and checking during traversal.
Example 1:
ImportJava.util.*;classForeach { Public Static<T>voidSOP (T-t) {System.out.println (t); } Public Static voidMain (string[] args) {ArrayList<String> Al =NewArraylist<string>(); Al.add ("ABC"); Al.add ("BCD"); Al.add ("Kef"); //1. Traditional for loop traversal (obtained by corner label) for(intI=0;i<al.size (); i++) {SOP (Al.get (i)); } SOP ("\ n"); //2. For loop traversal (iterator) for(Iterator<string> it2 =al.iterator (); It2.hasnext ();) {SOP (It2.next ()); } SOP ("\ n");/*//for Loop Traversal (enumeration of vector sets) for (enumeration<string> en = al.elements (); en.hasmoreelements ();) {SOP (En.nextelement ()); } sop ("\ n");*/ //3. For loop Enhanced traversal for(String s:al) {SOP (s); } }}
Using the For Advanced Traversal (foreach) in the Map collection
///Example 2:
ImportJava.util.*;classFOREACH2 { Public Static voidsop (Object obj) {System.out.println (obj); } Public Static voidMain (string[] args) {Map<String,Integer> HM =NewHashmap<string,integer>(); Hm.put ("A", 1); Hm.put ("B", 2); Hm.put ("C", 3); Set<String> keyset =Hm.keyset (); Set<Map.Entry<String,Integer>> EntrySet =Hm.entryset (); //after conversion to the set set, get the element directly with the iterator (method: KeySet ())Iterator<string> it1 =Keyset.iterator (); while(It1.hasnext ()) {String str=It1.next (); Integer in=hm.get (str); SOP ("Str:" +str+ "" + "in:" +In ); } SOP ("---------------------"); //gets the element with a for loop advanced traversal after conversion to set set for(String str:keyset) {SOP ("Str:" +str+ "::" + "in:" +hm.get (str)); } SOP ("---------------------"); //after conversion to the set set, get the element directly with the iterator (method: EntrySet ())Iterator<map.entry<string,integer>> it2 =Entryset.iterator (); while(It2.hasnext ()) {Map.entry<String,Integer> me =It2.next (); String Str=Me.getkey (); Integer in=Me.getvalue (); SOP ("Str:" +str+ "" + "in:" +In ); } SOP ("---------------------"); //gets the element with a for loop advanced traversal after conversion to set set for(map.entry<string,integer>Me:entryset) {SOP ("Str:" +me.getkey () + "..." + "in:" +Me.getvalue ()); } }}
Java: Collection for Advanced loop traversal