# 10-咸鱼学Java-Java中的二维数组

## 二维数组的定义和初始化

        //规则数组
int[][] a = new int[2][3];
int[][] a2 = {{1,2,3},{4,5,6}};
int[][] a3 = new int[][]{{1,2,3},{4,5,6}};
//不规则数组
int[][] a4 = new int[2][];
a4[0] = new int[3];
a4[1] = new int[2];

3种初始化方式其中a2和a3都已初始化，a和a4需要一个元素一个元素赋值。

        a[i][j] = k;

## 数组的遍历

1.for

    public static void show1(int[][] array){
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();
}
}

2.foreach

    public static void show2(int[][] array){
for( int[] brr: array ){
for(int i:brr){
System.out.print(i+" ");
}
System.out.println();
}
}

## 二维数组的拷贝

1.直接copy地址

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

array2改变，array也会改变因为他们指向同一块内存空间。

2.直接copy

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

for(int i = 0;i < array.length;i++){
for(int j = 0;j < array[i].length;j++){
array2[i][j] = array[i][j];
}
}

3.clone拷贝

    int[][] a = {{1,2,3},{4,5,6}};
int[][] b = new int[2][3];
b = a.clone();
show1(a);//可以打印数组的函数
show1(b);
System.out.println("改");
a[0][0] = 10086;
show1(a);
show1(b);

1 2 3 4 5 6 ++++++++++++++++++++++++ 1 2 3 4 5 6 ++++++++++++++++++++++++ 改 10086 2 3 4 5 6 ++++++++++++++++++++++++ 10086 2 3 4 5 6 ++++++++++++++++++++++++ 

    int[][] a = {{1,2,3},{4,5,6}};
int[][] b = new int[2][3];
for (int i = 0; i < a.length; i++) {
b[i] = a[i].clone();
}
show1(a);
show1(b);

System.out.println("改");
a[0][0] = 10086;
show1(a);
show1(b);

1 2 3 4 5 6 ++++++++++++++++++++++++ 1 2 3 4 5 6 ++++++++++++++++++++++++ 改 10086 2 3 4 5 6 ++++++++++++++++++++++++ 1 2 3 4 5 6 ++++++++++++++++++++++++ 
4.System.arraycopy

5.Arrays.copyOf

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120