Hi, i only know the Java basics and really need help! I have a class called temporaryHolder which holds an arrayList of 54 cards. However, I need to get elements out of this arraylist and need to add them to stacks in another class.

Q1) How can I access all the elements in this arraylist as I am in another class called
public class pile.

Q2)If the user says I want 3 piles, I can get the user input by the scanner but How do I create the 3 piles(stacks)

for(int i=0; i <3; i++){
Card c = new Stack();
}

This aint working.

Q3) Once the piles have been created, lets say 3. I need to add elements from the arraylist to the piles(stacks) This is what needs to happen.

Pile 1 Pile 2 Pile3
ArrayListElement1 ArrayListElement2 ArrayListElement3
ArrayListElement4 ArrayListElement5 ArrayListElement6

And so on....

I only know the java basics and find this very complicated. I have spent many hours trying to solve this problem but cannot. Can somebody please help?

1) Create a accessor method in your class with the ArrayList which returns it. So, something like this:

public ArrayList<Card> getCardArrayList() {
	return listOfCards; //Where listOfCards is the ArrayList of cards
}

2) Create a new Stack and then use the push(...) method to add Cards.

//A single stack
Stack s=new Stack();
//An array of stacks with length 3
Stack[] stackArray=new Stack[3];
//If you want to take in user input...
int numOfPiles=scan.nextInt(); //Assuming scan is a Scanner 
Stack[] stackArray2=new Stack[numOfPiles];

//n.b. To initialize each stack in an array
for(int i=0; i<stackArray2.length; i++)
	stackArray2[i]=new Stack();

3) Add each element like this:

Stack s=new Stack();
s.push(listOfCards.get(index)); //Where listOfCards is the ArrayList and index is index of the desired element

Edited 6 Years Ago by coil: n/a

import java.util.*;
//This is a new class that will hold the piles.
public class Piles {
	//CardStorage is the class that holds the arraylist.
	private cardStorage b;
	private Stack s;
	private Stack[] stackArray;

public Piles(){
	b = new cardStorage();
	s = new Stack();
	stackArray = new Stack[3];
}

public void inialiseStack(){
for(int i=0; i<stackArray.length; i++)	
	stackArray[i]=new Stack();
 	
}


public void push(){
//The other class has a return method which returns the arrayList. The code below gets the arraylist.
b.getAListCard();
Stack s = new Stack();
//cards and index are underlined in red..it cannot find the arraylist. Even though I have a return method.
s.push(cards.get(index));
}
This article has been dead for over six months. Start a new discussion instead.