增强for循环

增强for循环只能用在数组、或实现了Iterable接口的集合类上。

eg.增强for循环遍历数组

@Test
public void test1() {
   int arr[] = {1, 2, 3};
   for (int num : arr) {
      System.out.println(num);
   }
}

增强for循环遍历list集合

@Test
public void test2() {
        List list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        for (Object obj : list) {
            int i = (Integer) obj;
            System.out.println(i);
        }
    }

下面看下传统方式遍历Map

传统方式一:

@Test
 public void test3() {
        Map map = new LinkedHashMap();
        map.put("1", "aaa");
        map.put("2", "bbb");
        map.put("3", "ccc");
        // 传统方式1
        Set set = map.keySet();
        Iterator it = set.iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            String value = (String) map.get(key);
            System.out.println(key + "=" + value);
        }
    }

传统方式二:

@Test
public void test4() {
        Map map = new LinkedHashMap();
        map.put("1", "aaa");
        map.put("2", "bbb");
        map.put("3", "ccc");
        // 传统方式2
        Set set = map.entrySet();
        Iterator it = set.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Entry) it.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            System.out.println(key + "=" + value);
        }
    }

增强for循环遍历Map

方式1:

@Test
 public void test5() {
        Map map = new LinkedHashMap();
        map.put("1", "aaa");
        map.put("2", "bbb");
        map.put("3", "ccc");
        // 增强for 取map 的第一种方式
        for (Object obj : map.keySet()) {
            String key = (String) obj;
            String value = (String) map.get(key);
            System.out.println(key + "=" + value);
        }

方式2:

@Test
public void test6() {
        Map map = new LinkedHashMap();
        map.put("1", "aaa");
        map.put("2", "bbb");
        map.put("3", "ccc");
        // 增强for 取map 的第二种方式
        for (Object obj : map.entrySet()) {
            Map.Entry entry = (Entry) obj;
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            System.out.println(key + "=" + value);
        }


你可能感兴趣的:(增强for循环)