0

I have a class to represent a player hand. However I have (in another class) an arraylist where I want to represent a bunch of playerhands. The problem is that I don't know how to add a card to the hand within the arraylist of many hands. I have a class representing both cards and a deck, which works well. I am just trying to understand how to add an object to an object within an arraylist. Thank you!

public class Hand{ 
ArrayList<Cards> hand;
public Hand(){
hand = new ArrayList<Cards>();}
public Class Pile{
ArrayList<Hand> = pile;
public Pile{
pile = new ArrayList<Hand>();
for(int i=0; i<5; i++){ pile.add(new Hand()); }
}
public void addToPile(int index, int position, Card card){
 pile.add(index, pile.get(i).add(Card));
}
asked Jan 19, 2019 at 11:25
2
  • 2
    Possible duplicate of How do i create a list of Objects in Java Commented Jan 19, 2019 at 11:46
  • Are you sure you want an ArrayList of player hands, wouldn’t it be better with a Map where the key identifies the player? Commented Jan 19, 2019 at 11:59

1 Answer 1

1

I guess you have an ArrayList like this:

ArrayList<Hand> hands = new ArrayList<>();

First you have to find your item's index -lets call it i- within hands. Then you can get your item from that list like this and put it into another variable. Hand myHand = hands.get(i); Then you can perform your add operation on myHand variable. Also, you can add a method to your class which takes a card and adds that card to the list of cards(hand).

myHand.addCard(card);
answered Jan 19, 2019 at 11:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.