2016-11-18 101 views
1

你好,我正在做一個撲克遊戲。我知道這個淺拷貝構造函數是不正確的,但它爲什麼不正確?陣列列表的淺拷貝

public Deck() { 
    cards = new ArrayList <Card>(); 

    for (int type= 0; type<=4; type++){ 
     for (int value=1; value<9; value++){ 
      Card newCard = new Card (value, type); 
      cards.add(newCard); 
     } 
    } 

} 

public Deck(Deck other) { 
    ArrayList<Card> cardsCopy = cards; 

    } 

回答

1
public Deck(Deck other) { 
    ArrayList<Card> cardsCopy = cards;  
    } 

這裏cardsCopy是不相關的一個Deck實例。它是一個孤立的變量,只要構造函數完成執行,變量就不會再存在。
若要擁有otherDeck的淺拷貝,您應分配給您正在創建的副本的cards字段,以及從other實例引用的cards字段。

淺拷貝構造函數可以是:

public Deck(Deck other) { 
    cards = other.cards; 
} 

但是當你在你的問題的標題,因爲cards場要求無論是在原和副本指的是不是ArrayList淺表副本同一個對象。

要與的ArrayList淺拷貝淺拷貝構造函數,你可以這樣做:

public Deck(Deck other) { 
    cards = new ArrayList<Card>(other.cards); 
} 

或使用ArrayList定義的clone()方法:

public Deck(Deck other) { 
    cards = other.cards.clone(); 
}