将数组转换为ArrayList

Saa*_*ana 80 java arrays list arraylist blackjack

我在将数组转换为ArrayListJava时遇到了很多麻烦.这是我现在的阵列:

Card[] hand = new Card[2];
Run Code Online (Sandbox Code Playgroud)

"手"拥有一系列"卡片".这看起来像是ArrayList什么样的?

Kal*_*Kal 86

这会给你一个清单.

List<Card> cardsList = Arrays.asList(hand);
Run Code Online (Sandbox Code Playgroud)

如果你想要一个arraylist,你可以做到

ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));
Run Code Online (Sandbox Code Playgroud)

  • 不!这给出了一个对象,它作为底层对象周围的`List`包装器.与真正的`ArrayList`不同,生成的`List`不可调整大小,并且尝试将`.add`元素添加到它的末尾将导致`UnsupportedOperationException`. (10认同)

twa*_*249 33

就像ArrayList那条线一样

import java.util.ArrayList;
...
ArrayList<Card> hand = new ArrayList<Card>();
Run Code Online (Sandbox Code Playgroud)

要用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
Run Code Online (Sandbox Code Playgroud)

另请阅读http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html


Eng*_*uad 13

List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
Run Code Online (Sandbox Code Playgroud)