java - 创建 <Fish> arrayList 深拷贝

标签 java deep-copy copyonwritearraylist

无论出于何种原因,当我尝试为植物数组列表创建深拷贝时,我收到一个空指针异常,但我不知道为什么。

/**
 * Copy Constructor. Since landscape is immutable in the scope of our
 * project, you could do a simple reference copy for it. However, Fish and
 * Plants are mutable, so those lists must be copied with a DEEP copy! (In
 * other words, each fish and each plant must be copied.)
 */



private ArrayList<Fish> fish;
private ArrayList<Plant> plants;
private int[][] landscape;

public Model(Model other) {
    this.landscape = other.landscape;

    for(Fish fishy: other.fish){
        this.fish.add(new Fish(fishy));
    }

    for(Plant planty: other.plants){
        this.plants.add(new Plant(planty));
    }
}

最佳答案

您还没有初始化鱼和植物

public Model(Model other) {
    fish = new ArrayList<Fish>();
    plants = new ArrayList<Plant>();
    this.landscape = other.landscape;

    for(Fish fishy: other.fish){
        this.fish.add(new Fish(fishy));
    }

    for(Plant planty: other.plants){
        this.plants.add(new Plant(planty));
    }
}

关于java - 创建 <Fish> arrayList 深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20445754/

相关文章:

java - RESTEasy - @Path 需要完整路径吗?

java - Flink 在 timeWindow 上应用函数

java - 如何为 firebase 中的现有子项添加新的 "key-value"对

c# - 如何执行未标记为可序列化的对象的深层复制(在 C# 中)?

python - 使从 boost-python 类继承的 Python 类可复制

路亚: copying a table efficiently (deep copy)

java - 如何原子地替换非同步并发列表或数组

Java Arraylist.retainAll() 返回意外的空列表

java - 将文本文件数据添加到数组java

Java - 并发清除列表