binary101
binary101

Reputation: 1013

Java - Iterate an ArrayList and Transferring the elements

My program creates a deck of cards and deals them all out to 4 different hands. This is my code. It creates the 4 hands and deals the cards to each of them.

    Hand[] hands = new Hand[4];
       for(int i=0; i<hands.length; i++){
           hands[i] = new Hand();
       }
       for(int i=0; i<=Deck.size()+8; i++){
           for(Hand hand : hands){
               hand.addSingleCard(Deck.deal());
           }
       }

Now i have 4 hands, each with 13 cards, I want to iterate over the first hand, removing each card and add it to the second hand so Hand 1 has 0 cards and Hand 2 has 26. What is the best way to implement this?

Im self learning, so if you have a method thats different to what someone else has posted, i'd still love to see it :)

Upvotes: 0

Views: 137

Answers (2)

jma127
jma127

Reputation: 1432

Assuming that the card data structure in your Hand class is an array or Collection, you can use a for-each loop.

static void transferCards (Hand from, Hand to) {
    for (Card card : from.cards) {
        to.addSingleCard(card);
    }
    from.cards.clear();
}

Feel free to replace the from.cards with whichever variable represents your cards.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691685

Assuming Hand holds its cards into a Collection<Card> (i.e. a List<Card> or a Set<Card> for example):

public void transferAllCardsToOtherHand(Hand hand) {
    hand.cards.addAll(this.cards);
    this.cards.clear();
}

Upvotes: 2

Related Questions