下面的程序演示了增强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());
}
}
注意:
增强for循环只能够遍历数组和实现了Iteratable接口的对象
不适合于并行遍历多个集合的循环中
for-each是顺向的迭代器,如果只想访问一些元素请使用传统for