JDK5-增强for循环

2017-01-09  本文已影响0人  Josaber

下面的程序演示了增强for循环在数组及集合中的应用:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Foreach {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] ints = new int[] { 1, 2, 3 };
        for (int i : ints)
            System.out.print(i);

        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 3; i++)
            list.add(i + 1);
        for (int i : list)
            System.out.print(i);

        Set<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < 3; i++)
            set.add(i + 1);
        for (int i : set)
            System.out.print(i);

        Map<Integer, String> map = new HashMap<Integer, String>();
        for (int i = 0; i < 3; i++)
            map.put(i + 1, String.valueOf(i + 1));
        for (Entry<Integer, String> entry : map.entrySet())
            System.out.print(entry.getKey() + entry.getValue());
    }
}

注意:

上一篇下一篇

猜你喜欢

热点阅读