「笔记」Java:数组

数组03:数组使用

AvatarYuan·2024-08-18·28

数组的元素类型和数组的大小都是确定的,所以当处理数组元素时候,我们通常使用基本循环或者 ForEach 循环。

【该实例完整地展示了如何创建、初始化和操纵数组】

public class TestArray {
    public static void main(String[] args) {
        double[] myList = {1.9, 2.9, 3.4, 3.5};
        // 打印所有数组元素
        for (int i = 0; i < myList.length; i++) {
            System.out.println(myList[i] + " ");
        }
        // 计算所有元素的总和
        double total = 0;
        for (int i = 0; i < myList.length; i++) {
            total += myList[i];
        }
        System.out.println("Total is " + total);
        // 查找最大元素
        double max = myList[0];
        for (int i = 1; i < myList.length; i++) {
            if (myList[i] > max) {
                max = myList[i];
            }
        }
        System.out.println("Max is " + max);
    }
}

1. For-Each 循环

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

语法格式如下:

for(type element: array){
    System.out.println(element);
}

【示例】

public static void main(String[] args) {
    double[] myList = {1.9, 2.9, 3.4, 3.5};
    // 打印所有数组元素
    for (double element: myList) {
        System.out.println(element);
    }
}

2. 数组作方法入参

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

例如,下面的例子就是一个打印 int 数组中元素的方法:

public static void printArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i] + " ");
    }
}

3. 数组作返回值

public static int[] reverse(int[] list) {
    int[] result = new int[list.length];
    for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
        result[j] = list[i];
    }
    return result;
}

以上实例中 result 数组作为函数的返回值。