0
我有这个对象,我标记为父对象,并且我想创建一个我称之为子对象的方法的副本(方法生成子对象)。当我实例化子对象时,将父对象的属性传递给构造函数。我一直遇到的问题是,当我通过调用更新方法来编辑孩子时,父母会发生同样的修改。我需要父母保持不变以让位给更多副本,这里可能是什么问题?任何帮助表示赞赏:)复制对象更改源对象,Java
import javax.swing.*;
import java.util.*;
public class State
{
private int[][] switches;
private int[][] lights;
private int numMoves;
public State(int[][] initSwitches,int[][] initLights,int numMoves)
{
this.switches = initSwitches;
this.lights = initLights;
this.numMoves = numMoves;
}
public int[][] getSwitches()
{
return switches;
}
public int[][] getLights()
{
return lights;
}
public int getNumMoves()
{
return numMoves;
}
public void updateState(int row, int col)
{
this.toggleSwitch(row,col);
this.toggleLight(row,col);
if(row+1 <= 4)
{
this.toggleLight(row+1,col);
}
if(row-1 >= 0)
{
this.toggleLight(row-1,col);
}
if(col+1 <= 4)
{
this.toggleLight(row,col+1);
}
if(col-1 >= 0)
{
this.toggleLight(row,col-1);
}
}
public void toggleSwitch(int row, int col)
{
if(this.switches[row][col] == 1)
{
this.switches[row][col] = 0;
}
else if(this.switches[row][col] == 0)
{
this.switches[row][col] = 1;
}
}
public void toggleLight(int row,int col)
{
if(this.lights[row][col] == 1)
{
this.lights[row][col] = 0;
}
else if(this.lights[row][col] == 0)
{
this.lights[row][col] = 1;
}
}
public State[] generateChildren(int numChildren)
{
int count = 0;
State[] children = new State[numChildren];
for(int i=0;i<numChildren;i+=1)
{
children[i] = new State(this.switches,this.lights,0);
}
for(int i=0;i<5;i+=1)
{
for(int j=0;j<5;j+=1)
{
if(this.switches[i][j] == 0)
{
children[count].updateState(i,j);
LightsOutSolver.printState(children[count]);
count+=1;
}
}
}
return children;
}
}
看到这个问题:http://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object -in-java的 –