binary101
binary101

Reputation: 1013

Java Constructor to take an array?

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?

Upvotes: 1

Views: 314

Answers (3)

Fritz
Fritz

Reputation: 10045

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.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213193

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.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533432

I would have one constructor to do both.

public Hand(Card... cards) {
    hand = Arrays.asList(cards);
}

Or an ArrayList copy as Rohit Jain suggests.

Upvotes: 7

Related Questions