Convert an array into an ArrayList [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-03 18:28:14

问题


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?


回答1:


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




回答2:


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));



回答3:


List<Card> list = new ArrayList<Card>(Arrays.asList(hand));



回答4:


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);
}


来源:https://stackoverflow.com/questions/9811261/convert-an-array-into-an-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!