Java Object-Array副本少了1个

时间:2015-04-09 12:49:39

标签: java copy

public void arrayUpdate(int counter,int counter2){
    int counterShipMemory=0;
    this.playerMemory2= new Player[this.playerMemory.length];
    for(int i = 0; i< this.playerMemory.length;i++){
    this.playerMemory2[i] = this.playerMemory[i];
    }
    this.playerMemory2[counter].shipMemory= new Ship[this.playerMemory2[counter].shipMemory.length-1];
    for(int counter3=0;counter3 <this.playerMemory[counter].shipMemory.length;counter3++){
        if(counter3!=counter2){
            this.playerMemory2[counter].shipMemory[counterShipMemory]=this.playerMemory[counter].shipMemory[counter3];
            counterShipMemory++;
        }
    }
    this.playerMemory[counter].shipMemory = new Ship[playerMemory2[counter].shipMemory.length];
    for(int counter3=0;counter3 <playerMemory2[counter].shipMemory.length;counter3++){
        this.playerMemory[counter].shipMemory[counter3]=playerMemory2[counter].shipMemory[counter3];
    }

说明: counter是来自一个玩家的数组ID。

counter2是应该删除的船舶的数组ID。

问题出在第7行(this.playerMemory2[counter].shipMemory= new Ship)。

如果我开始此行shipMemory playerMemory2playerMemory更改。但为什么?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

他们改变了两者,因为它们是同一个对象:

for(int i = 0; i < this.playerMemory.length; i++){
    this.playerMemory2[i] = this.playerMemory[i];
}

使用此循环,两个数组引用相同的对象(playerMemory[i] == playerMemory2[i],同一内存地址的对象)。因此,如果您更改shipMemory的{​​{1}},则还会更改playerMemory2[i]的{​​{1}}。

为防止这种情况,您可以克隆每个对象。如果您实现了shipMemory方法,那将是一个简单的解决方法:

playerMemory[i]

现在,只有clone()的{​​{1}}会发生变化。