JDK5-增强for循环
下面的程序演示了增强for循环在数组及集合中的应用:
1 import java.util.ArrayList; 2 import java.util.HashMap; 3 import java.util.HashSet; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.Map.Entry; 7 import java.util.Set; 8 9 public class Foreach { 10 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 int[] ints = new int[] { 1, 2, 3 }; 14 for (int i : ints) 15 System.out.print(i); 16 17 List<Integer> list = new ArrayList<Integer>(); 18 for (int i = 0; i < 3; i++) 19 list.add(i + 1); 20 for (int i : list) 21 System.out.print(i); 22 23 Set<Integer> set = new HashSet<Integer>(); 24 for (int i = 0; i < 3; i++) 25 set.add(i + 1); 26 for (int i : set) 27 System.out.print(i); 28 29 Map<Integer, String> map = new HashMap<Integer, String>(); 30 for (int i = 0; i < 3; i++) 31 map.put(i + 1, String.valueOf(i + 1)); 32 for (Entry<Integer, String> entry : map.entrySet()) 33 System.out.print(entry.getKey() + entry.getValue()); 34 } 35 }
注意:
增强for循环只能够遍历数组和实现了Iteratable接口的对象
不适合于并行遍历多个集合的循环中
for-each是顺向的迭代器,如果只想访问一些元素请使用传统for