• Java Data Structures Tutorial

Printing the elements of a Stack



You can print the contents of the stack directly, using the println() method.

System.out.println(stack)

The Stack class also provides iterator() method. This method returns the iterator of the current Stack. Using this you can print the contents of the stack one by one.

Example

import java.util.Iterator;
import java.util.Stack;

public class PrintingElements {
   public static void main(String args[]) {
      Stack stack = new Stack();
      stack.push(455);
      stack.push(555);
      stack.push(655);
      stack.push(755);
      stack.push(855);
      stack.push(955);
      System.out.println("Contents of the stack :");	
      Iterator it = stack.iterator();
      
      while(it.hasNext()) {
         System.out.println(it.next());    	  
      }
   }
}

Output

Contents of the stack :
455
555
655
755
855
955
Advertisements