Java 对象数组副本少 1 个

标签 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)。

如果我开始这一行,playerMemory2 处的 shipMemoryplayerMemory 会发生变化。但为什么?我该如何解决这个问题?

最佳答案

它们都会改变,因为它们是同一个对象:

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/

相关文章:

java - 如何使任意字体文件可用于 Java?

java - 用实际值替换环境变量占位符?

mysql - 将数据库中的 MySQL 父项和所有相关子项记录复制到新 ID

在 C 中创建结构的副本

c# - 在 C# 中有效地从二维数组中提取向量

java - 在 jTable 中编辑后如何保存单元格中的数据(自动保存)?

java - 如何在 Eclipse 中备份用户库?

java.util.UUID.randomUUID().toString() 长度

Java ZipFileSystem 属性

postgresql - 如何将数据从一个数据库移动到另一个数据库