0

I am trying to create an ArrayList of Card objects. This will represent the users hand. I have not really worked with arraylist before so any help would be appreciated. Below is my current attempt:

class Hand {

public static final int CARDS = 4;
ArrayList<Card> hand = new ArrayList<Card>();

public Hand(){

    for(int i=0; i < CARDS; i++){
    hand.add(new Card());
    }
}

Is this correct? and Specially if it is not correct, could somebody point out what I am doing wrong?

3
  • Looks fine, does it run? Commented Nov 21, 2013 at 18:15
  • why not try this on a compiler. Commented Nov 21, 2013 at 18:15
  • Just add a main() function and run it! Commented Nov 21, 2013 at 18:17

3 Answers 3

1

The easiest way to find out is to compile the program and run it. :)

That being said, it looks fine. The only thing I would change is:

ArrayList<Card> hand = new ArrayList<Card>();

to:

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

If you are using Java 7, you can get rid of the second generic-parameter:

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

Typing with interfaces is a good habit to get into since it is easier for you to switch implementations later (like if you wanted to use LinkedList<T> instead).

Sign up to request clarification or add additional context in comments.

3 Comments

As of Java 7 I believe the second generic declaration isn't necessary either. e.g. Foo<Generic> var = new Foo();
@Rogue Correct. But I am not sure what version of Java OP is using so I just left it like his question. :) But I have edited the answer to include the information.
@Rogue You still need a generic declaration, you can just use the so-called "diamond operator": Foo<Generic> var = new Foo<>();. If you just do new Foo(), that's a raw type just like in Java 5 or 6, and you'll get the same unchecked cast warning.
0

Overall it seems correct, however you are just adding new Card objects without any sort of (known) randomization, so all the cards will be the same as far as I'm aware.

2 Comments

My card class handles the randomization, Thanks for your response
Best of luck on your program then :)
0

Seems good, just a small suggestion:

ArrayList<Card> hand = new ArrayList<Card>();

to:

List<Card> hand = new ArrayList<>(); //in java 7 the diamond symbol in right is allowed

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.