102

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Saatana
  • 1,177
  • 3
  • 9
  • 8

4 Answers4

89

This will give you a list.

List<Card> cardsList = Arrays.asList(hand);

If you want an arraylist, you can do

ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));
Kal
  • 24,724
  • 7
  • 65
  • 65
  • 10
    Nope! This gives an object that acts as a `List` wrapper around an underlying object. Unlike a real `ArrayList`, the resulting `List` is not resizable, and attempts to `.add` elements to the end of it will result in `UnsupportedOperationException`. – Adam Norberg Mar 21 '12 at 19:14
39

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

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
twain249
  • 5,666
  • 1
  • 21
  • 26
  • Thank you! One last quick question.. how would I accept an arraylist into a method? Right now I have: public void getHandValue(ArrayList< Card > hand) {...} The arraylist is in my main args. Just the word "ArrayList" is coming up as an error. – Saatana Mar 21 '12 at 19:36
  • you should be able to have a method signature `void getHandValue(ArrayList hand)` the problem is more than likely when you are calling that method. – twain249 Mar 21 '12 at 20:29
15
List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

declaring the list (and initializing it with an empty arraylist)

List<Card> cardList = new ArrayList<Card>();

adding an element:

Card card;
cardList.add(card);

iterating over elements:

for(Card card : cardList){
    System.out.println(card);
}
bpgergo
  • 15,669
  • 5
  • 44
  • 68