我有一个数组int [3] [3],其初始位置为:
(A)
block[0][0] = 1;
block[0][1] = 1;
block[0][2] = 1;
block[1][0] = 1;
block[1][1] = 1;
block[1][2] = 1;
block[2][0] = 1;
block[2][1] = 0;
block[2][2] = 1;
//Visually
1 1 1
1 1 1
1 0 1
我有一个采用" 0"元素并使用upper元素进行更改,因此下一个状态是:
(B)
1 1 1
1 0 1
1 1 1
但问题是,我想用这个位置创建一个新数组(称为aux)并且不要超过块数组(A)
这是我的代码:
//Creating array B
int[][] aux = new int[3][3];
aux = block; //load the values of original array
aux[line][row] = aux[line-1][row];
aux[line-1][row] = 0;
但是当我检查输出时,我也覆盖了原始数组(块)。
所以我有数组BLOCK和数组AUX具有相同的值,并且不要使用原始数据保持数组BLOCK。
=============================================== ============================
编辑:
我尝试使用clone和copyOf函数,但结果也影响了原始数组。 这是我的代码:
System.out.println("INITIAL BLOCK VALUES");
System.out.println(
bloco[0][0] +""+
bloco[0][1] +""+
bloco[0][2] +
"\n"+
bloco[1][0]+
bloco[1][1]+
bloco[1][2]+
"\n"+
bloco[2][0] +
bloco[2][1] +
bloco[2][2]
);
//Cloning original array to a new one
int[][] aux = bloco.clone();
//Here what I'm doing is changing the first element of AUX, just for test
aux[0][0] = 9;
// Block array shouldnt be affected! Lets check it out:
System.out.println("FINAL BLOCK VALUES");
System.out.println(
bloco[0][0] +""+
bloco[0][1] +""+
bloco[0][2] +
"\n"+
bloco[1][0]+
bloco[1][1]+
bloco[1][2]+
"\n"+
bloco[2][0] +
bloco[2][1] +
bloco[2][2]
);
OUPUT是:
INITIAL BLOCK VALUES
111
111
101
FINAL BLOCK VALUES
911
111
101
有什么想法吗?
OBS:此代码位于名为" Node"的类的函数内部。哪个构造函数是:
public Nodo( int[][] blocos )
{
this.bloco = blocos;
}
答案 0 :(得分:0)
此程序显示原始数组复制到新数组而不更改原始数组值
class Array
{
public static void main (String[] args) {
int[][] block = new int[3][3];
//load the values of original array
block[0][0] = 1;
block[0][1] = 1;
block[0][2] = 1;
block[1][0] = 1;
block[1][1] = 1;
block[1][2] = 1;
block[2][0] = 1;
block[2][1] = 0;
block[2][2] = 1;
int[] [] aux=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<block[i].length;j++)
{
aux[i][j]=block[i][j];
}
System.out.print("\n");
}
aux[1][1]=0;//replace array value
aux[2][1]=1;//replace array value 1
System.out.print("Old Array \n");
for(int i=0;i<3;i++)
{
for(int j=0;j<block[i].length;j++)
{
System.out.print(block[i][j]);
}
System.out.print("\n");
}
System.out.print("New Array \n");
for(int i=0;i<3;i++)
{
for(int j=0;j<block[i].length;j++)
{
System.out.print(aux[i][j]);
}
System.out.print("\n");
}
}
}
outpur:aux的数组是
Old Array
111
111
101
New Array
111
101
111