这是我的作业(作业)。我真的希望有人可以帮我弄清楚我做错了什么。
当我尝试创建State对象时 state = new State(tablesize,tb);
然后尝试复制 州st2 =新州(州);
然后尝试修改状态中的数据 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();
}
}
答案 0 :(得分:1)
您的复制构造函数已创建table
2D数组的浅层副本。原始对象和副本都引用相同的原始数组,因为您将数组引用从原始对象分配给新对象。这对于int
值来说很好,因为值会被复制。但是对于那些对obejct的引用被复制的对象来说,这是不可能的。
而不是仅仅复制对数组的引用......
table = s.gettable();
您需要创建一个新的复制数组:
table = new int[arraysize][arraysize];
// 2 nested for loops here to copy the contents
答案 1 :(得分:0)
public int[][] gettable()
{
return table;
}
因此,两个状态对象都引用相同的数组。您需要为每个实例创建一个新数组。