0

So I'm trying to create "piles" of cards in a class called Table using an ArrayList with stacks inside of it that contain the card objects (which are defined in a separate class).

I initialized it like so:

private MyArrayList<MyStack<Card>> piles;    

public Table()
{
  MyStack<Card> piles = new MyStack<>();
}

My issue is that I can't figure out how to add things to and from the stack inside the ArrayList. Is my initialization of it wrong? If so, how can I fix it?

Note: MyArrayList and MyStack are just slightly different versions of ArrayList and Stack essentially.

Gavin Reid
  • 13
  • 3
  • The "duplicated" questions I put up talk about "lists of lists". But essentially, it doesnt matter if you talk list of list, list of stack, or list of whatever collection. – GhostCat Oct 10 '17 at 14:38

2 Answers2

0

Iterate through the list here piles, push card in the Stack.

for (MyStack cards: piles) {
    cards.push(new Card);
}
brijesh
  • 760
  • 6
  • 4
0

The variable names are a little confusing. Consider:

// private MyArrayList<MyStack<Card>> piles; 
private final ArrayList<Stack<Card>> allPiles; 

public Table() {
    // MyStack<Card> piles = new MyStack<>();
    allPiles = new ArrayList<>();
}

then you can do something like this:

public void addCardToPile(Card card, int pileIndex) {
   while (allPiles.size() < pileIndex) {
       allPiles.add(new Stack<Card>());
   }

   allPiles.get(pileIndex).push(card);
}


public Card getTopCardFromPile(int pileIndex) {
   while (allPiles.size() < pileIndex) {
       allPiles.add(new Stack<Card>());
   }

   if (allPiles.get(pileIndex).isEmpty()) {
       return null;
   }

   return allPiles.get(pileIndex).pop();
}

But it's not clear if ArrayList is the most appropriate here. Consider a Map<Integer, Stack<Card>> allPiles, and instead of pileIndex have something like pileNumber. Or Map<String, Stack<Card>> allPileswith pileName.

Andrew S
  • 2,509
  • 1
  • 12
  • 14
  • Unfortunately changing the variable names listed is a no no due to it being a class project assignment, as is adding methods and such (yes, a coding class that doesn't let you try different things), but I'm going to try what you said and see if I get my program to work. – Gavin Reid Oct 10 '17 at 14:30
  • Then tell your instructor that he is teaching you *garbage*. There is absolutely no sense in having a local variable *piles* shadowing a field *piles* ... and even using different types. Names are important. They mean something. If your instructor really insists on such details ... woha. – GhostCat Oct 10 '17 at 14:36
  • Well, your solution did help me out though! I can finally make the card game work so thank you. – Gavin Reid Oct 10 '17 at 14:38