在不覆盖旧数组的情况下更改数组的值



这里我试图将数组顺时针旋转90度,我将"mat"的值分配给了"new array"(行:9(。当我试图覆盖"新数组"的值时(第13行(,"mat"数组的值也被覆盖,导致实际值发生变化,并在结果上出现错误,建议我进行一些编辑以停止覆盖"mat’数组

class maxpop {
public static void main(String[] args) {
Rotation();
}
static void Rotation(){
int[][] mat = {{0,0,0},{1,1,1},{2,2,2}};
int[][] newarray = new int[mat.length][mat.length];
int p;
newarray=mat;
for (int i = 0; i < newarray.length; i++) {
p=mat.length-1;
for (int j = 0; j <newarray.length; j++,p--) {
newarray[i][j] = newarray[p][i];
}

}
for (int i = 0; i < newarray.length; i++) {
for (int j = 0; j < newarray.length; j++) {
System.out.print(newarray[i][j]);
}
//p--;
System.out.println();
}}}

当您执行newarray=mat时,两个数组都指向同一个对象,其中一个的更改将更改另一个停止覆盖垫子阵列并旋转90度

class maxpop {
public static void main(String[] args) {
Rotation();
}
static void Rotation(){
int[][] mat = {{0,0,0},{1,1,1},{2,2,2}};
int[][] newarray = new int[mat.length][mat.length];
int p;
int k=0;
while (k<no of times you want to rotate) {
for (int i = 0; i < newarray.length; i++) {
p =mat.length-1;
for (int j = 0; j <newarray.length; j++,p--) {
newarray[i][j] = mat[p][i];
System.out.print(newarray[i][j]);
} 
System.out.println();   
}
int[][] newarrray_2=new int[newarray.length] 
[newarray.length];/*everytime the loop runs it will create 
newobject with 0 
values, if you don't create a new array each time 
newarry,newarray_2 
will 
point the same object,and newarray will not get initialised to 
0 later*/
mat=newarray;//mat will get overwrite 
newarray=newarrray_2;/*a new 0 value will be initialised to 
new array*/
k++;
}
}}

在此代码中:

int[][] mat = {{0,0,0},{1,1,1},{2,2,2}};   // (A)
int[][] newarray = new int[mat.length][mat.length];   // (B)
int p;
newarray=mat;

newarray=mat;将对旧数组的引用分配给newarray变量。您在(B(中创建并分配给newarray的新阵列将不再可访问。matnewarray都将指向(A(中声明的相同数组。你需要去掉那条线。您还需要从mat阵列进行复制。

public class MaxPop {
public static void main(String[] args) {
rotation();
}
static void rotation() {
int[][] mat = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 } };
int[][] newarray = new int[mat.length][mat.length];
int p;
for (int i = 0; i < newarray.length; i++) {
p = mat.length - 1;
for (int j = 0; j < newarray.length; j++, p--) {
newarray[i][j] = mat[p][i];
}
}
for (int i = 0; i < newarray.length; i++) {
for (int j = 0; j < newarray.length; j++) {
System.out.print(newarray[i][j]);
}
System.out.println();
}
System.out.println();
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
System.out.print(mat[i][j]);
}
System.out.println();
}
}
}

打印:

210
210
210

000
111
222

最新更新