Java Stack class

Introduction

Stack is a subclass of Vector that implements a standard last-in, first-out stack.

Stack only defines the default constructor.

 P:Full source
// Demonstrate the Stack class. 
import java.util.*; 
  
public class Main { 
  static void showpush(Stack<Integer> st, int a) { 
    st.push(a); /*from w w w.jav  a 2s.  com*/
    System.out.println("push(" + a + ")"); 
    System.out.println("stack: " + st); 
  } 
 
  static void showpop(Stack<Integer> st) { 
    System.out.print("pop -> "); 
    Integer a = st.pop(); 
    System.out.println(a); 
    System.out.println("stack: " + st); 
  } 
 
  public static void main(String args[]) { 
    Stack<Integer> st = new Stack<Integer>(); 
 
    System.out.println("stack: " + st); 
    showpush(st, 42); 
    showpush(st, 66); 
    showpush(st, 99); 
    showpop(st); 
    showpop(st); 
    showpop(st); 
 
    try { 
      showpop(st); 
    } catch (EmptyStackException e) { 
      System.out.println("empty stack"); 
    } 
  } 
}
import java.util.EmptyStackException;
import java.util.Stack;

public class Main {
  public static void main(String[] args) {
    Stack<Number> stack = new Stack<>(); // create a Stack

    stack.push(12L); //from  ww w  .ja va2 s .c  om
    printStack(stack);
    stack.push(345);
    printStack(stack);
    stack.push(1.1230F); 
    printStack(stack);
    stack.push(1234.5678D); 
    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> stack) {
    if (stack.isEmpty())
      System.out.printf("stack is empty%n%n"); // the stack is empty
    else // stack is not empty
      System.out.printf("stack contains: %s (top)%n", stack);
  }
}



PreviousNext

Related