Package Cn.jdk.foreach;import Java.util.hashmap;import Java.util.map;public class Foreachtest {public static void main ( String[] args) {int[] arr = {1,2,3};for (int a:arr) {System.out.println (a + "\ T");} System.out.println ("=============================="); map<string,string> map = new hashmap<string,string> (), Map.put ("1", "one"), Map.put ("2", "one"), Map.put ("3 "," three "); Map.put (" 4 "," Four "), Map.put (" 5 "," Five "),//map.keyset (): Loops through all the keys of the map, Map.keyset () returns the set type, The set can be enhanced for traversal. For (String Key:map.keySet ()) {String value = Map.get (key);//Gets the corresponding value by key System.out.println (key+ "=" +value);}}
<p> enhanced for pros and cons </p><p>l can only traverse arrays or collections from beginning to end, not just parts; </p><p>l cannot get the current element subscript while traversing a list or array </ P><p>l enhanced for use is simple, which is its only advantage; </p><p>l enhanced for is a bit easier than using iterators! </p>
Map does not implement the Iterable interface, so you cannot use the enhanced for to traverse it directly!
Java Enhanced for Loop