Searching...
Saturday, 6 October 2012

Java Collections: Stack Example

04:43

          The Stack class represents a last-in-first-out (LIFO) stack of objects
          The common push and pop operations are provided
          As well as a method to peek at the top item on the stack is also provided
image
 

Example

package mycollectiontest;

import java.util.Stack;

public class CollectionExample {

public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.push("First Person");
stack.push("Second Person");
stack.push("Third Person");
System.out.println("Total contents" + stack);
System.out.println("Total Size" + stack.size());
System.out.println("Pop 1" + stack.pop());
System.out.println("Pop 2 " + stack.pop());
System.out.println("Total contents after poping : " + stack);
System.out.println("Total Size after poping :" + stack.size());
}

}

Output

Total contents[First Person, Second Person, Third Person]
Total Size3
Pop 1Third Person
Pop 2 Second Person
Total contents after poping : [First Person]
Total Size after poping :1

0 comments: