在Java中的两个类之间共享对象
如何在两个相似的类之间共享对象? 例如,我想在一个游戏中有两个玩家:人类和计算机 他们将共享一个包含变量ArrayList cardList的Deck类 在游戏过程中,人类和计算机对象需要同时访问卡片列表以绘制卡片 cardList arraylist作为构造函数中的参数传递给人工或计算机,以将卡片添加到自己的手牌arraylist。在我将一些卡片添加到手牌arraylist后,是否可以返回更改的cardList arraylist在Java中的两个类之间共享对象,java,Java,如何在两个相似的类之间共享对象? 例如,我想在一个游戏中有两个玩家:人类和计算机 他们将共享一个包含变量ArrayList cardList的Deck类 在游戏过程中,人类和计算机对象需要同时访问卡片列表以绘制卡片 cardList arraylist作为构造函数中的参数传递给人工或计算机,以将卡片添加到自己的手牌arraylist。在我将一些卡片添加到手牌arraylist后,是否可以返回更改的cardList arraylist 抱歉,如果我的解释令人困惑ArrayList是一个可变容器。如
抱歉,如果我的解释令人困惑
ArrayList
是一个可变容器。如果在构造时将其传递给两个对象,则其上发生的任何变化都将反映在任何其他引用上。基本上我要说的是:将ArrayList传递给两个对象,在其中一个对象中进行更改,更改将在另一个对象中可用,反之亦然
事实已经如此。如果你有三门课,人类,计算机和甲板 人:
public class Human {
private Deck commonDeck;
private card currentCard;
public Human(Deck deck) {
commonDeck = deck;
}
public pickCard() {
currentCard = commonDeck.removeLastCard();
}
}
计算机:
public class Computer {
private Deck commonDeck;
private card currentCard;
public Computer(Deck deck) {
commonDeck = deck;
}
public pickCard() {
currentCard = commonDeck.removeLastCard();
}
}
甲板:
正如代码注释中所解释的,人和计算机对象共享同一个deck对象。它们共享对Deck实例的相同引用。因此,无论你在人类身上做了什么,都会在计算机上看到。谢谢。忘了它是通过引用传递的。这是正确的,但我仍然建议传递
deck
而不是ArrayList
。
public class Deck {
private List<Card> cards;
public Deck(){
cards = new ArrayList<Card>();
/*populate the list*/
}
public Card removeLastCard() {
return cards.remove(cards.size() - 1);
}
}
public static void main() {
Deck deck = new Deck();
Human human = new Human(deck);
Computer computer = new Computer(deck);
//human and computer share the same deck object
human.pickCard(); //human will remove a card from the list deck.cards
//The deck object in computer is the same as in human
//So coputer will see that a card has been removed
}