gpt4 book ai didi

java - 将数据存储到不同的对象但被覆盖

转载 作者:行者123 更新时间:2023-12-02 05:20:41 24 4
gpt4 key购买 nike

我有一个问题,我对此完全不知道,所以我做了一个类似的编码并在这里发布我的问题希望你们能帮助我。这是我的主要类(class):

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

这是我的新类(class):

package test;

import java.util.ArrayList;
import java.util.List;

public class newclass {

private Object[][] array;
private int x, y;
List<Integer> slot = new ArrayList<>();

public newclass(Object[][]array, int x, int y){
this.array = array;
this.x = x;
this.y = y;
}

public void storedata(){
int i=0;
while( i < 2 ){
int a,b;
a=(int) Math.floor(Math.random()*(x));
b=(int) Math.floor(Math.random()*(y));
if(NC[a][b]==null){
slot.add(0);
NC[a][b] = slot;
slot = new ArrayList<>();
}
else{
List templist = (List)NC[a][y];
templist.add(0);
}
i++;
}
}

public void display(){
for(int i=0; i<x ;i++){
for(int j=0; j<y ;j++){
List templist = (List)array[i][j];
if(templist==null){
System.out.print("");
}
else{
for (int k = 0; k < templist.size(); k++) {
System.out.print(templist.get(k));
}
}
System.out.print(",");
}
System.out.print("\n");
}
}

}

我的问题是主类中的第二个循环覆盖了“0|”再次在数组 NC 中

最佳答案

您将相同的对象数组传递给 newclass 的两个实例。因此,当您在其中一个中更改它时,更改将针对另一个中指向的同一数组进行。

当您将数组或对象传递给方法时,您传递的是其引用,而不是它的新副本。

如果您希望每个 newclass 实例都有一个单独的、私有(private)的、无法从外部访问的对象数组,则必须在构造函数内使用 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("========================");
}
}

关于java - 将数据存储到不同的对象但被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26547941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com