Search code examples
javaarrayslistarraylistblackjack

Convert an array into an ArrayList


I'm having a lot of trouble turning an array into an ArrayList in Java. This is my array right now:

Card[] hand = new Card[2];

"hand" holds an array of "Cards". How this would look like as an ArrayList?


Solution

  • As an ArrayList that line would be

    import java.util.ArrayList;
    ...
    ArrayList<Card> hand = new ArrayList<Card>();
    

    To use the ArrayList you have do

    hand.get(i); //gets the element at position i 
    hand.add(obj); //adds the obj to the end of the list
    hand.remove(i); //removes the element at position i
    hand.add(i, obj); //adds the obj at the specified index
    hand.set(i, obj); //overwrites the object at i with the new obj
    

    Also read this http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html