0
public class War {

    public static void main(String args[])
    {
            ArrayList<Integer> deck = new ArrayList<>(List.of(2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 
            5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 
            12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14));
        
            // Creates a deck and shuffles it
            Collections.shuffle(deck);
    
            System.out.println(deck);
    
            ArrayList<Integer> player1 = new ArrayList<>();
            ArrayList<Integer> player2 = new ArrayList<>();
    
            System.out.println(player2);
            System.out.println(player1);  
    }    
}

This is for my card war game where I want to split the deck arraylist in half (2 lists) and then be able to use those 2 lists as the cards for the 2 players.

c0der
  • 18,467
  • 6
  • 33
  • 65
foscool
  • 25
  • 2

1 Answers1

4

You can use subList:

List<Integer> deck1 = deck.subList(0,deck.size()/2);
List<Integer> deck2 = deck.subList(deck.size()/2,deck.size ());

Note that these are views of the original List, so changes in these sub-llsts will be reflected in the original List.

If you want to avoid that, you can make copies:

List<Integer> deck1 = new ArrayList<>(deck.subList(0,deck.size()/2));
List<Integer> deck2 = new ArrayList<>(deck.subList(deck.size()/2,deck.size ()));

Or, as Basil commented, if you wish the lists to be immutable, use:

List<Integer> deck1 = List.of(deck.subList(0,deck.size()/2));
List<Integer> deck2 = List.of(deck.subList(deck.size()/2,deck.size ()));
Eran
  • 387,369
  • 54
  • 702
  • 768