简体   繁体   中英

Remove all elements in one list and add to another list - Java

So I'm trying to remove all cards from a player's 'Rack' (an ArrayList) and put it in the discard pile (Stack), one by one. So far I have the following code which I've come to realize will stop once it hits 5. (Note: each players rack has 10 cards).

        int rackSize = player.getPlayerRack().getRack().size(); // rackSize = 10
        for (int i = 0; i < rackSize; i++) {
            getDeck().getDiscardPile().add(player.getPlayerRack().getRack().remove(i));
        }

My question is how do I remove all items in the players 'Rack' so the rackSize = 0, and add all of them to the discard pile?

Terribly sorry if this is confusing. You can generalize this by saying there are 10 integers in an ArrayList<Integer> hand , so: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] . How would you remove all items from this list and add them to a Stack<Integer> discardPile ?

What's happening is as you're removing the elements from Rack , you're still incrementing with i++ , meaning that the new value at the old index i is still left behind. What you'll want to do is change your code to this:

int rackSize = player.getPlayerRack().getRack().size(); // rackSize = 10
for (int i = 0; i < rackSize; i++) {
    getDeck().getDiscardPile().add(player.getPlayerRack().getRack().remove(0));
}

This way, you're always reaching into the first new element in the Rack until it's empty, assuming Rack is not repopulated while this code is executing.

Use 0 instead of i to access the ArrayList.

When you remove an element, it is no longer in the ArrayList so you have to keep this is mind - further references through the array index should be decremented 1 in each iteration. As a result you probably want to access the first item every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM