0

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

/**
 * 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));
    }
}
4

3 回答 3

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));
    }
}
于 2013-12-07T19:46:41.530 回答
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 是否为空也很重要。在您的情况下,您可能最终尝试迭代一个空列表。

于 2013-12-07T19:48:56.557 回答
1

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

例如:

public Model() {
    fish = new ArrayList<Fish>();
    plants = new ArrayList<Plant>();
}
于 2013-12-07T19:49:10.950 回答