Java Question

print method for Generic Stack in java

I have a problem finding a solution for this peculiar problem.
I have this class of a generic Stack.

class Pilita<T> {
private int tam;
private T[] arregloPila;
private int tope;

@SuppressWarnings("unchecked")
public Pilita(int tam) {
this.tam=tam;
arregloPila=(T[])new Object[tam];
tope=-1;
}
public void push(T valor){
if(pilaLlena()){
throw new StackFullException("No se puede meter el: "+"["+valor+"]"+" La pila esta llena");
}
arregloPila[++tope]=valor;
}
public T pop() {
if(pilaVacia()){
throw new StackEmptyException("La pila esta vacia");
}
return arregloPila[tope--];
}
public boolean pilaVacia(){
return (tope == -1);
}
public boolean pilaLlena(){
return (tope==tam-1);
}
public int contar(){
return(tope+1);
}


And I want to know how to implement a method to print the stack, because i have a method for normal stacks, but it doesn't seems to work with Generic Stack.

Any help would be Helpful.

Answer

To print the all the stack, you only need to check if the stack is not empty

public static void main(String[] args) {
        Pilita pila = new Pilita(3);
        pila.push("1");
        pila.push("2");
        pila.push("3");
        while (!pila.pilaVacia()) {
            System.out.println("Pil pop " + pila.pop());
        }
    }
Comments