Latest web development tutorials

Java Stack class

Stack is a subclass of Vector, which implements a standard LIFO stack.

Stack only defines the default constructor to create an empty stack. In addition to the stack includes all the methods defined by the Vector, also defines some of their methods.

Stack()

In addition to all the methods defined by the Vector, and he defines methods:

No. Method Description
1 boolean empty ()
To test whether the stack is empty.
2 Object peek ()
See the top of the stack of objects, but does not remove it from the stack.
3 Object pop ()
Remove the top of the stack object, and as the value of this function returns the object.
4 Object push (Object element)
Pushes an item onto the top of the stack.
5 int search (Object element)
Returns the location of the object in the stack, with 1 as the base.

Examples

The following program illustrates this collection supports several methods

import java.util.*;

public class StackDemo {

   static void showpush(Stack st, int a) {
      st.push(new Integer(a));
      System.out.println("push(" + a + ")");
      System.out.println("stack: " + st);
   }

   static void showpop(Stack st) {
      System.out.print("pop -> ");
      Integer a = (Integer) st.pop();
      System.out.println(a);
      System.out.println("stack: " + st);
   }

   public static void main(String args[]) {
      Stack st = new Stack();
      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");
      }
   }
}

The above examples compiled results are as follows:

stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack