2016-10-31 32 views
0

我有一個問題找到這個奇怪的問題的解決方案。 我有這個類的通用堆棧。在java中的通用堆棧的打印方法

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

而且我想知道如何實現的方法來打印堆棧,因爲我有正常棧的方法,但它似乎並不與通用協議棧工作。

任何幫助將是有幫助的。

+0

哪裏是你的方法來打印通用堆棧,而什麼不是工作? –

+0

[打印Java數組的最簡單方法是什麼]的可能重複(http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – Tom

回答

0

要打印所有堆棧,你只需要檢查堆棧不爲空

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