简体   繁体   中英

How do I add an object to an arraylist within an arraylist of objects?

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));
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM