Java:for循环出现for(int i : arr)

  在看书时,注意到作者使用的for循环中出现for(int i : arr),之前没有接触过,不知其作用,于是写了个test测试了其作用。结果发现这是一个遍历循环。

1 public class test {
2     public static void main(String[] args) {
3         int[] arr = new int[] {1, 2, 3};
4         for(int i : arr) {
5             System.out.println(i);
6         }
7     }
8 }

经查阅资料,for(:){...}是JDK1.5增强for循环也叫for-each.是为了方便遍历数组和collection的.由于collection都实现了Iterable(可迭代的)接口,所以可以用for-each来遍历容器类。

原文地址:https://www.cnblogs.com/LGMing/p/4440994.html