JDK5-增强for循环

下面的程序演示了增强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 list = new ArrayList();
        for (int i = 0; i < 3; i++)
            list.add(i + 1);
        for (int i : list)
            System.out.print(i);

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

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

注意:

  • 增强for循环只能够遍历数组和实现了Iteratable接口的对象
  • 不适合于并行遍历多个集合的循环中
  • for-each(增强for循环)是顺向的迭代器,如果只想访问一些元素请使用传统for

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