1 PackageP2;2 3 Importjava.util.ArrayList;4 ImportJava.util.HashMap;5 Importjava.util.List;6 ImportJava.util.Map;7 8 Public classForeachdemo {9 Ten Public Static voidMain (string[] args) { One /* A * foreach statement: - * Format: - * for (type variable: Collection Collection | array) the * { - * - * } - * + * What is the difference between traditional for and advanced for? - * Traditional for can be executed many times for a statement, since the increment and condition of the control loop can be defined. + * Advanced for is a simplified form. It must have a target that is traversed. The target is either an array or a collection single-column collection A * at * Traversal of an array if you are just getting the elements in the arrays, you can use the advanced for - * If you want to manipulate the angular label of an array, we recommend that you use legacy for. - */ - -list<string> list =NewArraylist<string>(); -List.add ("ABC1"); inList.add ("ABC2"); -List.add ("ABC3"); to + for(String s:list) - { the System.out.println (s); * } $ Panax Notoginseng - int[] arr = {3,1,5,7,4}; the for(intI:arr) + { A System.out.println (i); the } + - $ /* $ * Can I use the advanced for Traversal map collection? cannot be used directly, but you can turn the map into a single-column set, you can use the - */ - themap<integer,string> map =NewHashmap<integer,string>(); -Map.put (3, "Zahngsan");WuyiMap.put (at "Zahngsan"); theMap.put ("Zahngsan")); -Map.put (1, "Zahngsan"); Wu - for(Integer key:map.keySet ()) About { $String value =Map.get (key); -System.out.println (key+ "::" +value); - } - A for(Map.entry<integer, string>Me:map.entrySet ()) + { theInteger key =Me.getkey (); -String value =Me.getvalue (); $System.out.println (key+ "::" +value); the } the the } the -}
Java Learning Notes foreach statement (Advanced for)