javacodex.com
Java Examples
Java Examples
memu home questions

Stack Example

The Stack class represents a last-in-first-out (LIFO) stack of objects.

push() pushes an object onto the top of the stack.
peek() returns the stack the object at the top of the stack (leaving the object on the stack)
pop() returns the object at the top of the stack (removing the object from the stack)
empty() tests if the stack is empty

Source: (StackExample.java)

import java.util.*;
 
public class StackExample {
 
   public static void main(String args[]) {
      Stack<Integer> stack = new Stack<Integer>();
 
      // add elements the stack
      stack.push(111);
      stack.push(2);
      stack.push(3333);
      stack.push(44);
      stack.push(555);
 
      // search for element
      int position = stack.search(44); 
      System.out.println("Position of 44: " + position);
 
 
      // get the contents of the stack
      while(! stack.empty() ){
        System.out.println( stack.pop() );
      }
 
      // add to stack again 
      for(int i=0;i<5;i++){
        stack.push(i);
      }
 
      // show contents
      System.out.println("stack: " + stack);
 
      // use enhanced for to get contents of stack 
      for(int n: stack){
        System.out.println(n);
      }
   }
}
 

Output:

$ java StackExample 
Position of 44: 2
555
44
3333
2
111
stack: [0, 1, 2, 3, 4]
0
1
2
3
4

Contact: javacodex@yahoo.com