数组是每个编程语言的最常用的数据结构之一,二维数组应用场景比较广泛,其赋值方式比普通的数组要复杂一些。
静态初始化并赋值//二维数组 静态初始化 int[][] data = new int[][] { { 1, 2 }, { 2, 3 }, { 2, 3, 4 }, { 1, 2, 3, 4 } }; print(data);
动态赋值 //动态赋值 int[][] data2 = new int[3][2]; for (int i = 0; i < data2.length; i++) { for (int j = 0; j < data2[i].length; j++) { data2[i][j] = i * j; } } print(data2);
动态列赋值 //动态列 int[][] data1 = new int[3][]; for (int i = 0; i < data1.length; i++) { data1[i] = new int[i + 1]; for (int j = 0; j < data1[i].length; j++) { data1[i][j] = i * j; } } print(data1);
遍历 private void print(int[][] data) { System.out.println("----------------------------------------------------"); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { System.out.println(String.format("data[%s][%s] = %s", i, j, data[i][j])); } } }