Java 将数组转换为 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9811261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert an array into an ArrayList
提问by Saatana
I'm having a lot of trouble turning an array into an ArrayList
in Java. This is my array right now:
我在将数组转换为ArrayList
Java中遇到了很多麻烦。这是我现在的数组:
Card[] hand = new Card[2];
"hand" holds an array of "Cards". How this would look like as an ArrayList
?
“手”持有一系列“卡片”。这看起来像一个ArrayList
?
采纳答案by twain249
As an ArrayList
that line would be
作为ArrayList
那条线将是
import java.util.ArrayList;
...
ArrayList<Card> hand = new ArrayList<Card>();
To use the ArrayList
you have do
使用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
Also read this http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
另请阅读此http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
回答by Eng.Fouad
List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
回答by Kal
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));
回答by bpgergo
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);
}