I'm writing a poker game, and have all of the cards stored in an arraylist created in the class Deck:
public class Deck {
ArrayList<Card> deck = new ArrayList<Card>();
Deck(){ //Build the deck in order.
for(int suit = 1; suit <= 4; suit++){
for(int rank = 1; rank <= 13; rank++){
Card card = new Card(rank, suit);
deck.add(card);
}
}
}
. . .
I want to have another class--Hand--draw the first five elements from the arraylist and put them into a new arraylist called myHand:
public class Hand {
ArrayList<Card> myHand = new ArrayList<Card>();
Deck deckObject = new Deck();
public void Draw(){ //Draws the top 5 cards of the deck and puts them in your hand ArrayList.
for(int i = 0; i <= 4; i++){
myHand.add(deckObject.deck.get(0));
deckObject.deck.remove(0);
}
}
. . . So far so good. When I display the hand ArrayList from the main class I get the first five cards in the deck. However, when I display the deck from the Deck class (after invoking the Draw() method) all 52 cards are still there.
If I create a getDeck() method in the Hand class and call it, the first five cards are removed as expected...
So it seems like I have one-way communication between these two classes; when I modify the ArrayList from the Hand class, the Deck class doesn't know about it, and it seems that each class is keeping a separate version of the ArrayList. What's going on here?