Java 将数据存储到不同的对象但被覆盖
我有一个问题,我完全不知道这一点,所以我做了一个类似的编码和张贴我的问题在这里希望你们能帮助我。这是我的主要课程:Java 将数据存储到不同的对象但被覆盖,java,arrays,nested,Java,Arrays,Nested,我有一个问题,我完全不知道这一点,所以我做了一个类似的编码和张贴我的问题在这里希望你们能帮助我。这是我的主要课程: package test; public class Test { public static void main(String[] args) { newclass [] NC; NC = new newclass[2]; Object[][] array = new Object[5][5]; int x=5, y=5; for (i
package test;
public class Test {
public static void main(String[] args) {
newclass [] NC;
NC = new newclass[2];
Object[][] array = new Object[5][5];
int x=5, y=5;
for (int i=0 ; i<2 ; i++){
NC[i]= new newclass(array, x, y);
}
//solve roomHC
for (int i=0 ; i<2 ; i++){
NC[i].storedata();
}
//display solution
for (int i=0 ; i<2 ; i++){
System.out.print("\n");
NC[i].display();
System.out.print("========================");
}
}
}
封装测试;
公开课考试{
公共静态void main(字符串[]args){
新类别[]NC;
NC=新的新类[2];
Object[][]数组=新对象[5][5];
int x=5,y=5;
对于(int i=0;i,您正在将相同的对象数组传递给newclass
的两个实例。因此,当您在其中一个实例中更改它时,将对指向另一个实例内部的相同数组进行更改
将数组或对象传递给方法时,传递的是它的引用,而不是它的新副本
如果希望每个newclass
实例都有一个单独的、私有的、从外部无法访问的对象数组,则必须在构造函数内部使用new
。例如:
public newclass(int x, int y){
this.NC = new Object[x][y];
this.x = x;
this.y = y;
}
然后像这样使用它:
public static void main(String[] args) {
newclass [] NC;
NC = new newclass[2];
int x=5, y=5;
for (int i=0 ; i<2 ; i++){
NC[i]= new newclass(x,y);
}
//solve roomHC
for (int i=0 ; i<2 ; i++){
NC[i].storedata();
}
//display solution
for (int i=0 ; i<2 ; i++){
System.out.print("\n");
NC[i].display();
System.out.print("========================");
}
}
publicstaticvoidmain(字符串[]args){
新类别[]NC;
NC=新的新类[2];
int x=5,y=5;
对于(int i=0;i当您使用Math.random()
设置a和b时,您如何期望一致的结果?同样slot=new ArrayList();
意味着您在循环的每次迭代中都要重新初始化列表,这样它就不会包含任何值。我已经编辑了我的问题,您可以再次检查。我想现在您删除了Math.random(),无论发生什么情况,两个对象中的结果都是相同的。它只会在两个对象的第二列中都放零。现在还不清楚您要在这里做什么。不,您不理解代码,那里有一个while循环,所以第二个循环是“0”我将在下一个专栏中介绍我的预期结果。对不起,我不太理解您的解释…但在主类中,我声明了数组NC[5][5]的大小你不应该只是将我的方法添加到你的代码中,你还应该使用我提供的构造函数,而不是接受数组的构造函数。你不应该在主类中创建数组。我仍然感到困惑,这意味着我必须删除主类中的数组NC,如果它被删除,那么构造函数中应该不再有NC要传递。不,在ma中不是NC在课堂上。数组
在主课堂上。您使用的是相同的数组
,因此他们在同一个地方书写。对不起,我弄错了,现在我已经再次编辑了代码,请重新检查。
public static void main(String[] args) {
newclass [] NC;
NC = new newclass[2];
int x=5, y=5;
for (int i=0 ; i<2 ; i++){
NC[i]= new newclass(x,y);
}
//solve roomHC
for (int i=0 ; i<2 ; i++){
NC[i].storedata();
}
//display solution
for (int i=0 ; i<2 ; i++){
System.out.print("\n");
NC[i].display();
System.out.print("========================");
}
}