The Stacks class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek.

Creating Stack Objects

Stacks can be created with the default constructor:

Stack stack = new Stack();

Type-safe Stacks can be defined in the following way:

Stack<Obj> list = new Stack<Obj> ();
Stack<Integer> list = new Stack<Integer> (); // creates an integer stack

Operations on Stacks

In addition to the operations of Lists and Vectors, Stacks also provide the following operations:

  • Object push(Object element): Pushes an element on the top of the stack.
  • Object pop(): Removes and returns the top element of the stack. An exception is thrown if we call pop() when the invoking stack is empty.
  • Object peek(): Returns the element on the top of the stack, but does not remove it.
  • boolean empty(): It returns true if nothing is on the top of the stack. Else, returns false.
  • int search(Object element): It determines whether an object exists in the stack. If the element is found, it returns the position of the element from the top of the stack. Else, it returns -1.

Working with Stacks

The following java program demonstrates working with Stacks:

Stack<Integer> stack = new Stack<Integer>(); 

System.out.println(stack.peek()); // outputs 2
System.out.println(stack.pop()); // outputs 2
System.out.println(stack.peek()); // outputs 3
System.out.println(stack.pop()); // outputs 3
System.out.println(stack.pop()); // outputs 1
System.out.println(stack.empty()); // outputs true


results matching ""

    No results matching ""