7. 二维数组
7.1 定义
-
二维数组及就是数组的嵌套,数组的元素还是数组;
-
二维数组是一个 元素为一维数组 的一维数组;
-
语法上Java支持多维数组,但从内存分配原理的角度看,Java中只有一维数组,没有多维数组;
7.2 二维数组的初始化和赋值
7.2.1 长度已知
数据类型[][] 数组名 = new 数据类型[二维数组的长度][一维数组的长度];
double[][] height = new double[3][5];
height[0][0] = 156;
height[2][4] = 173;
7.2.2 二维长度已知
数据类型[][] 数组名 = new 数据类型[二维数组的长度][];
public static void main(String[] args){double[][] height = new double[3][];height[0] = new double[5];//指定二维数组中的元素一维数组的长度height[1] = new double[5];height[2] = new double[5];height[0][0] = 156;height[0][1] = 162;height[0][2] = 180;height[0][3] = 178;height[0][4] = 169;height[1][0] = 162;height[1][1] = 186;height[1][2] = 190;height[1][3] = 171;height[1][4] = 175;height[2][0] = 159;height[2][1] = 178;height[2][2] = 184;height[2][3] = 168;height[2][4] = 173;}
7.2.3 声明并赋值
public static void main(String[] args){double[][] height = {{156,162,169},{162,186,175},{159,178,184,168,173}};
}
7.3 遍历二维数组
public static void demo() {int[][] list = new int[5][];// 1. 赋值操作list[0] = new int[2];list[0][0] = 10;list[0][1] = 20;list[1] = new int[1];list[1][0] = 15;list[2] = new int[1];list[2][0] = 45;list[3] = new int[2];list[3][1] = 89;list[4] = new int[3];list[4][2] = 73;// {{10,20},{15},{45},{0,89},{0,0,73}}// 2. 遍历数组for (int i = 0; i < list.length; i++) {int[] arr = list[i];for (int j = 0; j < arr.length; j++) {System.out.printf("list[%d][%d]=%d \n", i, j, arr[j]);}}}
}
public static void demo() {int[][] list = {{1, 4}, {0, -10}, {9}, {8, -12, 7}};for (int i = 0; i < list.length; i++) {int[] arr = list[i];for (int j = 0; j < arr.length; j++) {System.out.printf("list[%d][%d]=%d \n", i, j, arr[j]);}}}
public static void task() {// 1. 声明二维数组int list[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7 } };// 2. 遍历数组listfor (int i = 0; i < list.length; i++) {// 3. 遍历内层数组for (int j = 0; j < list[i].length; j++) {System.out.printf("%d,", list[i][j]);// 1,2,3,4,5,6,7,}}}
// 遍历三维数组public static void task3() {// int arr[][][] = new int[3][2][1];int arr[][][] = {{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } },{ { 10, 11, 12 }, { 13, 24, 15 }, { 16, 17, 18 } },{ { 19, 20, 21 }, { 22, 23, 24 }, <