Stack Class in Collection Framework

public class Stack extends Vector
Stack class extends Vector class. The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty , and a method to search the stack for an item and discover how far it is from the top.
When a stack is first created, it contains no items.
Stack class features:
  1. Stack is used for Dynamic and Resizable-array implementation of the List interface.
  2. It is used to store an “insertion ordered” group of elements.
  3. It can contain duplicate elements.
  4. Implements all optional list operations, and permits all elements, including null.
  5. It is synchronized.
  6. The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.
  7. An Stack capacity is the size of the array used to store the elements in the list.
  8. As elements are added to an Stack, its capacity grows automatically.
Constructor of Stack
  1. Stack()
    It is used to create  an empty stack.
Method of Stack class
  1. public Object push(Object item)
             It is used to insert an item onto the top of this stack. This has exactly the same effect as: addElement(item).
  2. public Object pop( )
             It is used to remove the object at the top of this stack and returns that object as the value of this function.
  3. public Object peek( )
              It is used to looks at the object at the top of this stack without removing it
    from the stack.
  4. public boolean empty( )
               It is used to test stack is empty or not.
  5. public int search(Object o )
              It is used to search element the 1-based position where an object is on this stack. The topmost item on the stack is considered to be at distance 1.
Example of Stack class
import java.util.Stack; public class StackDemo { public static void main(String args[]) { Stack s = new Stack(); // Insert element to stack s.push("Welcome"); s.push("nsstudent"); s.push("."); // Show top of Stack System.out.println("Next: " + s.peek()); s.push("com"); // Delete element from stack System.out.println(s.pop()); // Search element to stack int count ="Welcome"); System.out.println("Count :"+ count); while (count != -1 && count > 1) { System.out.println("Deleted Element :"+s.pop()); count--; } System.out.println(s.pop()); System.out.println(s.empty()); } }

Next: .
Count :3
Deleted Element :.
Deleted Element :nsstudent
Download this example


Latest Tutorial

Most Visited Tutorial