二维数组
可以认为二维数组是元素为一维数组的数组
1. 声明二维数组
type[][] arrayName;
2. 初始化二维数组
(1)静态初始化
arrayName = new type[][]{{...}, {...}, ...};
- 若在声明时直接进行初始化,则可以省略new type[][]
- type[][] arrayName = {{...}, {...}, ...};
(2)动态初始化
arrayName = new type[outerLength][innerLength];
3. 访问二维数组
- 访问元素:arrayName[outerIndex][innerIndex]
- 访问长度:arrayName.length, arrayName[outerIndex].length
4. 综合代码 + 运行结果
package mulArray;
import java.util.Arrays;
public class app {
public static void main(String[] args) {
// 静态初始化
int[][] arr1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.deepToString(arr1));
// 动态初始化
int[][] arr2 = new int[5][2];
for (int i = 0; i < arr2.length; ++i) {
for(int j = 0; j < arr2[i].length; ++j) {
arr2[i][j] = (int) (Math.random() * 100 + 1);
}
}
System.out.println(Arrays.deepToString(arr2));
// 遍历二维数组
for (int i = 0; i < arr1.length; ++i) {
for(int j = 0; j < arr1[i].length; ++j){
System.out.print(arr1[i][j] + "\t");
}
System.out.println("");
}
// 本质是一维的
// 用动态的方式初始化的时候,外层的长度是一定要给的,内层数组的长度不指定可以
int[][] arr3 = new int[3][];
// 接着将它当成一维数组,给每个索引的位置去赋值
arr3[0] = new int[] {1, 6};
arr3[1] = new int[] {5, 63, 96, 36, 33};
arr3[2] = new int[] {11, 66};
System.out.println(Arrays.deepToString(arr3));
System.out.println("层行列");
// 更多的维度
int[][][] arr4 = {
{{1, 2, 6}, {2, 9}, {33}},
{{11}, {33, 22, 69}},
{{22}}
};
for (int i = 0; i < arr4.length; ++i) {
for (int j = 0; j < arr4[i].length; ++j) {
for (int k = 0; k < arr4[i][j].length; ++k) {
System.out.print(arr4[i][j][k] + "\t");
}
System.out.println(' ');
}
System.out.println(' ');
}
}
}