public class Stav implements Cloneable{
private int[] pole;
public Stav(int[] pole){
this.pole = pole;
}
public Stav(Stav a){
this.pole = a.pole;
}
public void move(boolean left){
int empty = findEmpty();
if(left){
this.pole[empty] = this.pole[empty - 1];
this.pole[empty - 1] = 0;
}
else{
this.pole[empty] = this.pole[empty + 1];
this.pole[empty + 1] = 0;
}
}
和
Jednotka pom = fronta.remove();
Stav nStav = new Stav(pom.getStav().getPole());
Stav pomStav = new Stav(nStav);
当我打电话时
pomStav.move(false);
nStav的值将与pomStav相同...有人可以帮助我吗?我在代码中还有更多的方法,但是它是如此之久,所以我没有像findEmpty等在这里复制。
最佳答案
public Stav(Stav a){
this.pole = a.pole;
}
调用此方法时,在将引用复制到对象时,两个实例之间共享基础
int[] pole
。代替复制引用,创建一个新数组并复制值:public Stav( Stav a )
{
this.pole = new int[ a.pole.length ];
for( int i = 0; i < this.pole.length; ++i )
this.pole[ i ] = a.pole[ i ];
}