arraylist的浅拷贝

时间:2016-11-18 18:20:39

标签: java arraylist constructor copy

您好,我正在制作扑克游戏。我知道这个浅拷贝构造函数不正确,但为什么它不正确?

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 个答案:

答案 0 :(得分:1)

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

此处cardsCopyDeck实例无关。它是一个孤立的变量,一旦构造函数完成执行就不再存在了 要拥有other Deck的浅表副本,您应该分配到正在创建的副本的cards字段,cardsother字段的引用实例。

浅拷贝构造函数可以是:

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

但是,由于原始版本和副本中的ArrayList字段都指向同一个对象,因此您在问题标题中询问的不是cards的浅层副本。

要拥有一个浅拷贝ArrayList的浅拷贝构造函数,你可以这样做:

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

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

public Deck(Deck other) {
   cards = other.cards.clone();
}  
相关问题