JDK1.5新特性(一)……Enhanced for Loop

援引

Enhanced for Loop - This new language construct eliminates the drudgery and error-proneness of iterators and index variables when iterating over collections and arrays.

用法

forenhance_thumb4

增强for循环代替了一些原来的for循环的使用,使语句含义上更合理

被遍历的表达式必须是数组类型或者实现了Iterable接口,循环变量前面除了可以加类型之外还可以加修饰符,例如final之类的

例子

   1: public static void main(String[] args) {
   2:     // TODO Auto-generated method stub
   3:     ArrayList<String> al = new ArrayList<String>();
   4:     al.add("1");
   5:     al.add("2");
   6:     al.add("3");
   7:     for(String str : al){
   8:         System.out.println(str);
   9:     }
  10:     
  11:     int[] arr = new int[]{1,2,3};
  12:     for(int i : arr){
  13:         System.out.println(i);
  14:     }
  15: }

原文地址:https://www.cnblogs.com/ShawnWithSmallEyes/p/3453913.html