ProgramingTip

배열을 ArrayList로 변환

bestdevel 2020. 10. 12. 07:54
반응형

배열을 ArrayList로 변환


이 질문에 이미 답변이 있습니다.

배열을 ArrayListJava 로 바꾸는 데 많은 문제가 있습니다. 이것은 지금 내 배열입니다.

Card[] hand = new Card[2];

"hand"는 "카드"의 배열을 보유합니다. 어떻게 생겼을까 ArrayList요?


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 도 읽어 읽어.


이것은 당신에게 목록을 줄 것입니다.

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

arraylist를 사용할 수 있습니다.

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

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

참고 URL : https://stackoverflow.com/questions/9811261/convert-an-array-into-an-arraylist

반응형