gpt4 book ai didi

java - 2 个分离的对象由于某种原因连接在一起

转载 作者:行者123 更新时间:2023-12-01 13:49:18 26 4
gpt4 key购买 nike

这是我的作业(作业)。我真的希望有人能帮助我弄清楚我做错了什么。

当我尝试创建一个 State 对象时状态 = 新状态(表大小,tb);

然后尝试复制状态 st2 = new State(状态);

然后尝试修改state中的数据state.placeNumber(1,1,3);

由于某种原因,st2中的数据也发生了变化。

下面是代码。我真的希望有人能指出我的错误在哪里。

谢谢

public class State 
{

private int arraysize;
private int lastfilledx;
private int lastfilledy;
private int table[][];

//constructor

public State()
{

}
public State(State s)
{
arraysize = s.getsize();
lastfilledx = s.lastindex_x();
lastfilledy = s.lastindex_y();
table = s.gettable();
}
public State(int size, int[][] tb)
{
arraysize = size;
table = new int[size][size];
//copy the initial table which is a 2d array
table = tb;
for (int i = 0 ; i < size; i++)
{
for(int j = 0 ; j < size ; j++)
{
if ( table[i][j] == 1)
{

lastfilledx = i;
lastfilledy =j;
break;
}
}
}
}

public void placeNumber(int i, int j, int nextvalue)
{
lastfilledx = i;
lastfilledy = j;
table[i][j] = nextvalue;
}

public void printoutput()
{
for (int i=0; i < arraysize; i++)
{
for (int j=0; j < arraysize; j++)
System.out.print(" " + table[i][j]);

System.out.println("");
}

System.out.println("last fill " + lastfilledx + " " + lastfilledy);
}

public int[][] gettable()
{
return table;
}

public int getsize()
{
return arraysize;
}
public int lastindex_x()
{
return lastfilledx;
}
public int lastindex_y()
{
return lastfilledy;
}
}




public class Dikuho extends State
{
private static State state;

public static void main(String[] args) {

int tablesize = 3;
int tb[][] = new int[tablesize][tablesize];

/*****HARDCODE the table data***/
for (int i=0; i < tablesize; i++)
for (int j=0; j < tablesize; j++)
tb[i][j] = 0;


//test case for 3x3
tb[2][2] = 1;
tb[0][0] = tablesize*tablesize;
tb[0][1] = 7;
tb[1][0] = 8;
tb[2][1] = 2;

//initialize the state
state = new State(tablesize, tb);


**//Here is where the problem is. I only change the data in state but the data in st2 is also changed. I'm not sure what happen here.**
State st2 = new State(state);
state.placeNumber(1,1,3);

st2.printoutput(); **//These both printout same output which is not correct**
state.printoutput();
}


}

最佳答案

您的复制构造函数已对 table 二维数组进行了浅复制。原始对象和副本都引用相同的原始数组,因为您将原始对象的数组引用分配给新对象。这对于 int 值来说很好,因为这些值是被复制的。但这对于对象来说不行,因为对象的引用被复制。

而不是仅仅复制对数组的引用...

table = s.gettable();

您需要创建一个新的复制数组:

table = new int[arraysize][arraysize];
// 2 nested for loops here to copy the contents

关于java - 2 个分离的对象由于某种原因连接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20084374/

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