Adamc23
Adamc23

Reputation: 157

How to obtain an ArrayList from ArrayList.subList?

I have an arraylist of a deck of cards ints 1-52 and they're shuffled and i'd like to basically split the deck in half indexes(0,25) and (26,51) to deal to two players. But I'm only seeing responses that say use List<> although I'd like to keep each players deck an arraylist as to not interfere with other already created methods. Is there a way to keep both players decks as arraylists?

import java.util.ArrayList;
import java.util.Collections;
public class Methods {
    public static ArrayList<Integer> deck =  new ArrayList<Integer>();
    public static ArrayList<Integer> deckPlayerOne =  new ArrayList<Integer>();
    public static ArrayList<Integer> deckPLayerTwo =  new ArrayList<Integer>();
    public static ArrayList<Integer> generateDeck(){
        for(int i=1; i<53; i++){
             deck.add(i);
        }
        return deck;
    }

    public static ArrayList<Integer> shuffle(){
        Collections.shuffle(deck);
        return deck;
    }

    public static void splitDeck(){
        // deckPlayerOne = deck.subList(0, 25); <---- location of error
    }

    public static ArrayList<Integer> playerOneDeck(){

        }

    }

    public static ArrayList<Integer> platerTwoDeck(){

    }
}

Upvotes: 4

Views: 4520

Answers (1)

morgano
morgano

Reputation: 17422

Maybe I didn't understand your question, but if you want an ArrayList to be split into other two you can use this:

    ArrayList myArrayList = new ArrayList();
    ArrayList part1 = new ArrayList(myArrayList.subList(0, 25));
    ArrayList part2 = new ArrayList(myArrayList.subList(26, 51));

Is that what you want?

Upvotes: 12

Related Questions