I have created a default constructor which creates an empty "hand".
public Hand() {
hand = new ArrayList();
}
Whats the most efficient way to have a second constructor take an Array of cards, then add them a hand?
I have created a default constructor which creates an empty "hand".
public Hand() {
hand = new ArrayList();
}
Whats the most efficient way to have a second constructor take an Array of cards, then add them a hand?
I would have one constructor to do both.
public Hand(Card... cards) {
hand = Arrays.asList(cards);
}
Or an ArrayList copy as Rohit Jain suggests.
Arrays.asList gives a fixed size ArrayList. of type: - java.util.Arrays.ArrayListhand won't be a List.hand. Problem is that, it is unmodifiable list. That's why I used a constructor in my version.hand or want to make it mutable with a copy.You can do it like this: -
public Hand(String[] hands) {
hand = new ArrayList<String>(Arrays.asList(hands));
}
Or, you can iterate over your string array, and add individual elements to your ArrayList.
public Hand(String[] hands) {
hand = new ArrayList<String>();
for (String elem: hands)
hand.add(elem);
}
P.S: - Always declare a Generic Type List.
ArrayList?hand is a List, as it should be)Arrays.asList returns a fixed size list right? So, if you just assign it, you won't be able to modify it.There's another option, Collections.addAll:
public Hand(Card[] cards) {
hand = new ArrayList<Card>();
Collections.addAll(hand, cards);
}
According to the documentation:
Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.