user123
user123

Reputation: 23

How to move a value from one ArrayList to another

I want to move a specific value from an array list to another, what is the best way to go about doing this? Here is some example code:

values from

ArrayList<CreateCard> deckArray = new ArrayList<CreateCard>();

to

ArrayList<CreateCard> playerHand = new ArrayList<CreateCard>();

Upvotes: 1

Views: 1557

Answers (5)

Terry Vogelsang
Terry Vogelsang

Reputation: 3

I would do a function like :

public void moveCard(List<CreateCard> playerHand, List<CreateCard> deckArray) {

    playerHand.add(deckArray.get[0])
    deckArray.remove(0)

}

Hope it helps.

Upvotes: 0

candied_orange
candied_orange

Reputation: 7334

I'm a big fan of helper functions:

public static void main(String[] args) {
    ArrayList<CreateCard> deckArray = new ArrayList<CreateCard>();
    deckArray.add(new CreateCard());
    deckArray.add(new CreateCard());

    ArrayList<CreateCard> playerHand = new ArrayList<CreateCard>();

    // Deal a card
    moveASpecificValue(deckArray, playerHand, 0);

    // Deal from the bottom of the deck
    moveASpecificValue(deckArray, playerHand, deckArray.size() - 1);
}

public static void moveASpecificValue( List<CreateCard> source, 
                                       List<CreateCard> destination, 
                                       int indexOfSpecificValue) {
    destination.add(source.remove(indexOfSpecificValue));
}

Upvotes: 1

Emz
Emz

Reputation: 1280

Some things first.

  • CreateCard is a class representing what? If it just represents a card then I'd name the class Card to avoid confusion.
  • Variables in java (just as methods) are usually named with lowerCamelCase meaning DeckArray to deckArray.
  • I recommend naming it to deckOfCards instead of deckArray as deckArray could be interpenetrated as an array of decks.
  • Can your array ever contain duplicate decks? As in are you playing with more one deck of cards? If not all its members will be unique. If so I recommend using HashSet instead or ArrayList.

Last the actual problem.

PlayerHand.add(DeckArray.remove(0));

That would remove the top card and add it to the PlayerHand.

Upvotes: 1

Joshua Powell
Joshua Powell

Reputation: 1

Just for loop through the ArrayList that you want to get the value from and when you come to the right index or criteria then just place the value inside the other array list.

Upvotes: 0

glu10
glu10

Reputation: 21

If you have the index i where the CreateCard is stored in DeckArray, you can just do:

PlayerHand.add(DeckArray.remove(i));

Upvotes: 1

Related Questions