你好,我在玩扑克游戏。我知道这个浅拷贝构造函数是不正确的,但是为什么它是不正确的?
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;
} 发布于 2016-11-18 19:24:42
public Deck(Deck other) {
ArrayList<Card> cardsCopy = cards;
} 这里,cardsCopy与Deck实例无关。它是一个孤立的变量,一旦构造函数完成它的执行,它就不再存在了。
要获得other Deck的浅拷贝,您应该将来自other实例的对cards字段的引用分配给正在创建的副本的cards字段。
浅拷贝构造函数可以是:
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();
} https://stackoverflow.com/questions/40683670
复制相似问题