Question

For whatever reason, when I try and create a deep copy for the plant array list, I get a null pointer exception and I don't know why.

/**
 * 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));
    }
}
Was it helpful?

Solution

You have not initialized fish and plants

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

OTHER TIPS

You should initialize your arrays:

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

}

Also, it's important to chance whether or not other.fish is null. In your case, you could have ended up trying to iterator over a null list.

I'm not sure without seeing the stacktrace, but have you initialized the to ArrayLists when Model - objects are created ?

e.g. :

public Model() {
    fish = new ArrayList<Fish>();
    plants = new ArrayList<Plant>();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top