创建<fish> arrayList深层复制</fish>

时间:2013-12-07 19:44:02

标签: 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));
    }
}

3 个答案:

答案 0 :(得分:3)

您尚未初始化鱼类和植物

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));
    }
}

答案 1 :(得分:1)

您应该初始化数组:

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

    if (other.fish != null) {
         for (Fish myFish : other.fish) {
               this.fish.add(new Fish(myFish));
         }
    }
    if (other.plants != null) {
         for (Plant myPlant : other.plants) {
               this.plants.add(new Plant(myPlant));
         }
    }

}

此外,无论other.fish是否为null都很重要。在您的情况下,您可能最终尝试在空列表上进行迭代。

答案 2 :(得分:1)

我不确定没有看到堆栈跟踪,但是在创建Model - 对象时是否已初始化为ArrayLists?

e.g。 :

public Model() {
    fish = new ArrayList<Fish>();
    plants = new ArrayList<Plant>();
}