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));
}
-
2Possible duplicate of How do i create a list of Objects in Javakostas poimenidhs– kostas poimenidhs2019年01月19日 11:46:08 +00:00Commented 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?Joakim Danielson– Joakim Danielson2019年01月19日 11:59:25 +00:00Commented Jan 19, 2019 at 11:59
1 Answer 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);