Java | 二维数组的使用

95 阅读2分钟

一、二维数组的声明

在Java中,二维数组可以看作是数组的数组。声明二维数组时,需要指定两个维度的大小。

demo:

public class TwoDimensionalArrayDeclaration {
    public static void main(String[] args) {
        // 声明一个3行4列的二维数组
        int[][] matrix = new int[3][4];
    }
}

二、二维数组的初始化

二维数组可以在声明的同时进行初始化。可以分别初始化每个内部数组,也可以直接在声明时初始化整个二维数组。

demo:

public class TwoDimensionalArrayInitialization {
    public static void main(String[] args) {
        // 初始化一个3行4列的二维数组
        int[][] matrix = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };
        // 另一种初始化方式
        int[][] dynamicMatrix = new int[3][];
        dynamicMatrix[0] = new int[]{1, 2, 3, 4};
        dynamicMatrix[1] = new int[]{5, 6, 7, 8};
        dynamicMatrix[2] = new int[]{9, 10, 11, 12};
    }
}

三、访问二维数组的元素

可以通过两个索引来访问二维数组的元素:第一个索引表示行,第二个索引表示列。

demo:

public class AccessTwoDimensionalArrayElements {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };
        // 访问元素
        System.out.println("访问元素matrix[1][2]:" + matrix[1][2]);  // 输出:访问元素matrix[1][2]:7
    }
}

四、遍历二维数组

可以使用嵌套的for循环来遍历二维数组的所有元素。

demo:

public class TraverseTwoDimensionalArray {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };
        // 遍历二维数组
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

五、二维数组的长度

二维数组的长度是指它包含的行数。每一行的长度(即列数)可能不同。

demo:

public class TwoDimensionalArrayLength {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3, 4},
            {5, 6},
            {7, 8, 9}
        };
        // 获取二维数组的长度
        System.out.println("二维数组的行数:" + matrix.length);  // 输出:二维数组的行数:3
        // 获取每一行的长度
        System.out.println("第一行的长度:" + matrix[0].length);  // 输出:第一行的长度:4
        System.out.println("第二行的长度:" + matrix[1].length);  // 输出:第二行的长度:2
        System.out.println("第三行的长度:" + matrix[2].length);  // 输出:第三行的长度:3
    }
}

以上就是本次分享的所有内容,感兴趣的朋友点个关注呀,感谢大家啦~