Java 中 for each

格式:

for(type element: array)

  {

        System.out.println(element);

  }

 

 

//ex:
{ public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; System.out.println("----foreach---"); for(int element:arr) { System.out.println(element); } System.out.println("----二维数组的foreach------"); //遍历二维数组 int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} ; for(int[] row : arr2) { for(int element : row) { System.out.println(element); } } //以三种方式遍历集合List List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); System.out.println("----方式1---"); //第一种方式,普通for循环 for(int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } System.out.println("----方式2---"); //第二种方式,使用迭代器 for(Iterator<String> iter = list.iterator(); iter.hasNext();) { System.out.println(iter.next()); } System.out.println("----方式3---"); //第三种方式,使用增强型的for循环 for(String str: list) { System.out.println(str); } } }

 

posted @ 2017-03-17 13:39  NHZ-M  阅读(203)  评论(0编辑  收藏  举报