# Java二维数组及其拷贝方式

//规则数组
int[][]array=new int [2][3];//二维数组定义
int[][]array1={{1,2,3},{4,5,6}};
int[][]array3=new int[][]{{1,2,3},{4,5,6}};
//不规则数组
int[][] array4 = new int[2][];
array4[0] = new int[3];
array4[1] = new int[2];



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();
}
}


forreach

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


forreach只能按顺序来访问数组中的每一个元素。

1.直接拷贝数组的地址

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


2 for循环拷贝

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];
}
}



TestArray[][] t1 = new TestArray[2][3];
for(int i = 0;i < t1.length;i++){
for(int j = 0;j < t1[i].length;j++){
t1[i][j] = new TestArray();
}
}

TestArray[][] t2 = new TestArray[2][3];

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

3 clone拷贝

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

array2 = array.clone();
show1(array);
System.out.println("======");
show1(array2);
array2[0][0] = 1000;
System.out.println("====改变==");
show1(array);
System.out.println("======");
show1(array2);


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

4 Arrays.copyOf与 Arrays.arraycopy

Arrays.arraycopy

int[][] array = {{1,2,3},{4,5,6}};
int[][] array2 = new int[2][3];
for(int i = 0;i < array.length;i++){
System.arraycopy(array[i], 0, array2[i],
0, array[i].length);


Arrays.copyOf

int[][] array = {{1,2,3},{4,5,6}};
int[][] array2 = new int[2][3];
for(int i = 0;i < array.length;i++){
array2[i] = Arrays.copyOf(array[i],array[i].length);


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

120