我在Java中将一个数组转换为ArrayList
遇到了很多问题。这是我现在的数组:
Card[] hand = new Card[2];
"hand"持有一个"Cards"数组。将其转化为ArrayList
后会是什么样子?
List<Card> cardsList = Arrays.asList(hand);
如果你想要一个ArrayList,可以这样做:
ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));
作为一个 ArrayList
,那行代码就是这样的:
import java.util.ArrayList;
...
ArrayList<Card> hand = new ArrayList<Card>();
要使用 ArrayList
,你需要做
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
还可以阅读这个http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
void getHandValue(ArrayList<Card> hand)
,问题很可能是在调用该方法时出现的。 - twain249List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
声明列表(并用空的ArrayList进行初始化)
List<Card> cardList = new ArrayList<Card>();
添加一个元素:
Card card;
cardList.add(card);
迭代元素:
for(Card card : cardList){
System.out.println(card);
}