96 votes

Convertir un tableau en une liste de tableaux (ArrayList)

J'ai beaucoup de mal à transformer une matrice en un ArrayList en Java. Voici mon tableau en ce moment :

Card[] hand = new Card[2];

La "main" contient un tableau de "cartes". A quoi cela ressemblerait-il en tant que ArrayList ?

86voto

Kal Points 14230

Vous obtiendrez ainsi une liste.

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

Si vous voulez une liste de tableaux, vous pouvez faire

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

37voto

twain249 Points 5292

En tant que ArrayList cette ligne serait

import java.util.ArrayList;
...
ArrayList<Card> hand = new ArrayList<Card>();

Pour utiliser le ArrayList vous avez fait

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

Lisez aussi ceci http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

13voto

Eng.Fouad Points 44085
List<Card> list = new ArrayList<Card>(Arrays.asList(hand));

1voto

bpgergo Points 9407

Déclarer la liste (et l'initialiser avec un arraylist vide)

List<Card> cardList = new ArrayList<Card>();

ajouter un élément :

Card card;
cardList.add(card);

itération sur les éléments :

for(Card card : cardList){
    System.out.println(card);
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X