2013-12-07 59 views
0

無論出於何種原因,當我嘗試爲植物數組列表創建深層副本時,出現空指針異常,我不知道爲什麼。創建<Fish> arrayList深度複製

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

謝謝你好先生 – user3011240

+0

歡迎。查看其他答案。 – 4J41

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爲空。在你的情況下,你可能會試圖通過空列表進行迭代。

1

我不確定沒有看到堆棧跟蹤,但是當Model - 創建對象時,是否已初始化爲ArrayLists?

例如:

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