Jupyter AI

21 数组之数组的常见操作

📅 发表日期: 2024年8月10日

分类: Java 入门

👁️阅读: --

在上一章,我们学习了如何初始化数组之数组(二维数组)。本章将介绍数组之数组的常见操作,包括如何访问、修改、遍历以及一些实用的例子。

1. 数组之数组的访问

访问一个数组之数组的元素,需要使用两个下标,第一个下标是行索引,第二个下标是列索引。其语法为:

arrayName[rowIndex][columnIndex]

示例

假设我们有一个 2 行 3 列的二维数组:

int[][] array = {
    {1, 2, 3},
    {4, 5, 6}
};

我们可以通过以下代码访问数组中元素:

int firstElement = array[0][0]; // 访问第一行第一列的元素,结果为 1
int secondElement = array[0][1]; // 访问第一行第二列的元素,结果为 2
int lastElement = array[1][2];    // 访问第二行第三列的元素,结果为 6

2. 数组之数组的修改

我们可以通过索引直接修改数组中某个元素的值:

array[1][2] = 10; // 将第二行第三列的元素修改为 10

在执行该语句后,array 的值变为:

{
    {1, 2, 3},
    {4, 5, 10}
}

3. 数组之数组的遍历

遍历二维数组通常使用嵌套的 for 循环。外层循环控制行,内层循环控制列。

示例代码

for (int i = 0; i < array.length; i++) { // 遍历每一行
    for (int j = 0; j < array[i].length; j++) { // 遍历每一列
        System.out.print(array[i][j] + " ");
    }
    System.out.println(); // 换行
}

输出

该代码将输出:

1 2 3 
4 5 10 

4. 实用案例:矩阵加法

接下来,我们将通过一个矩阵加法的例子来展示数组之数组的操作。

示例代码

public class MatrixAddition {
    public static void main(String[] args) {
        int[][] matrixA = {
            {1, 2, 3},
            {4, 5, 6}
        };
        
        int[][] matrixB = {
            {7, 8, 9},
            {10, 11, 12}
        };

        int rows = matrixA.length;
        int cols = matrixA[0].length;
        int[][] result = new int[rows][cols];

        // 矩阵加法
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[i][j] = matrixA[i][j] + matrixB[i][j];
            }
        }

        // 输出结果矩阵
        System.out.println("结果矩阵:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
    }
}

输出

这段代码将输出:

结果矩阵:
8 10 12 
14 16 18 

5. 总结

在本章中,我们学习了如何访问、修改和遍历数组之数组(二维数组)。通过具体的代码示例,我们掌握了基本的数组操作,以及如何利用这些操作来实现更复杂的功能,如矩阵加法。在下一章中,我们将讨论方法的定义与调用,为我们的编程之旅提供更强大的工具。