As shown below:
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", "two");map.put("3", "three");map.put("4", "four");map.put("5", "five");//map.keySet(): Looping through all keys of map. map.keySet() returns the Set type, and Set can be enhanced for traversal. for(String key:map.keySet()){String value = map.get(key);//Get the corresponding value through the key System.out.println(key+"="+value);}}}<p> Advantages and Disadvantages of Enhancement for</p><p>l can only traverse arrays or collections from beginning to end, but not only part;</p><p>l When traversing List or array, the current element subscript cannot be obtained;</p><p>l Enhancement for is simple to use, which is its only advantage;</p><p>l Enhancement for is a little more convenient than using iterators! </p>
Map does not implement the Iterable interface, so you can't just use enhancement for to iterate through it!
The above is the full content of the Java enhanced for loop implementation method brought to you by the editor. I hope it will be helpful to you and support Wulin.com more~