提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
包java.util的堆栈类。
import java.util.Stack;//N o w J a v a . c o m - 时代Java import java.util.EmptyStackException; public class Main { public static void main(String[] args) { Stack<Number> stack = new Stack<>(); // create a Stack // use push method stack.push(12L); // push long value 12L System.out.println("Pushed 12L"); printStack(stack); stack.push(34567); // push int value 34567 System.out.println("Pushed 34567");/*时 代 J a v a 公 众 号 - nowjava.com*/ printStack(stack); stack.push(1.0F); // push float value 1.0F System.out.println("Pushed 1.0F"); printStack(stack); stack.push(1234.5678); // push double value 1234.5678 System.out.println("Pushed 1234.5678 "); printStack(stack); // remove items from stack try { Number removedObject = null; // pop elements from stack while (true) { removedObject = stack.pop(); // use pop method System.out.printf("Popped %s%n", removedObject); printStack(stack); } } catch (EmptyStackException emptyStackException) { emptyStackException.printStackTrace(); } } // display Stack contents private static void printStack(Stack<Number> st