你好,我正在制作一款扑克游戏。我知道这个浅拷贝构造函数是不正确的,但为什么它不正确?
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;
}
最佳答案
public Deck(Deck other) {
ArrayList<Card> cardsCopy = cards;
}
这里cardsCopy
与Deck
实例无关。它是一个孤立的变量,一旦构造函数执行完毕,它就不再存在。
要获得 other
Deck
的浅拷贝,您应该将对 Deck 的引用分配给您正在创建的副本的
字段。cards
字段。来自 other
实例的 >cards
浅拷贝构造函数可以是:
public Deck(Deck other) {
cards = other.cards;
}
但正如您在问题标题中所问的那样,它不是 ArrayList
的浅拷贝,因为原始和副本中的 cards
字段都引用了相同的对象。
要拥有一个带有 ArrayList
浅拷贝的浅拷贝构造函数,您可以这样做:
public Deck(Deck other) {
cards = new ArrayList<Card>(other.cards);
}
或者使用ArrayList
中定义的clone()
方法:
public Deck(Deck other) {
cards = other.cards.clone();
}
关于java - 数组列表的浅拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40683670/