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
)。
如果我开始这一行,playerMemory2
处的 shipMemory
和 playerMemory
会发生变化。但为什么?我该如何解决这个问题?
最佳答案
它们都会改变,因为它们是同一个对象:
for(int i = 0; i < this.playerMemory.length; i++){
this.playerMemory2[i] = this.playerMemory[i];
}
通过此循环,两个数组引用相同的对象(playerMemory[i] == playerMemory2[i]
,位于同一内存地址的对象)。因此,如果您更改 playerMemory2[i]
的 shipMemory
,您也会更改 playerMemory[i]
的 shipMemory
。
为了防止这种情况,您可以克隆每个对象。如果您实现 clone()
方法,这将是一个简单的修复:
for(int i = 0; i < this.playerMemory.length; i++){
this.playerMemory2[i] = this.playerMemory[i].clone();
}
现在,只有 playerMemory2[i]
的 shipMemory
会发生变化。
关于Java 对象数组副本少 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29538983/