Java 读书笔记 (十三) for each 循环

JDK 1.5引进了一种新的循环类型,被称为foreach循环或者加强型循环,它能在不使用下标的情况下遍历数组。

实例:

 1 public class TestArray{
 2     public static void main(String[]args){
 3         double[] myList={1.9,2.9,3.4,3.5};
 4 
 5         // 打印所有数组元素
 6         for (double element: myList){
 7               System.out.println(element);
 8          }
 9      }
10 }
11 
12 /* 执行结果:
13     1.9
14     2.9
15     3.4
16     3.5
17 */

数组可以作为参数传递给方法.

 1 // 下面例子就是一个打印int数组中元素的方法:
 2 public static void printArray(int[] array){
 3     for(int i=0; i<array.length; i++){
 4          System.out.print(array[i]+" ");
 5     }
 6 }
 7 
 8 
 9 
10 //下面例子调用printArray方法打印出3、1、2、6、4和2.
11 printArray(new int[]}3,1,2,6,4,2});
12 
13 
14 
15 // 数组作为函数的返回值  (以下实例中result数组作为函数的返回值)
16 public static int[] reverse(int[] list){
17     int[] result =new int[list.length];
18     for (int i=0, j=result.length-1; i<list.length; i++, j--){
19         result[j]=list[i];
20     }
21     return result;
22 }
原文地址:https://www.cnblogs.com/cheese320/p/8110097.html