Stack

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

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations.

Constructor

Stack()
Creates an empty Stack.

Methods defined by Stack

boolean empty()
Tests if this stack is empty.
E peek()
Looks at the object at the top of this stack without removing it from the stack.
E pop()
Removes the object at the top of this stack and returns that object as the value of this function.
E push(E item)
Pushes an item onto the top of this stack.
int search(Object o)
Returns the 1-based position where an object is on this stack.

import java.util.Stack;

public class Main {

  public static void main(String[] args) {
    Stack stack = new Stack();
    for (int i = 0; i < 10; i++)
      stack.push(new Integer(i));
    System.out.println("stack = " + stack);

    stack.addElement("java 2s.com");
    System.out.println("element 5 = " + stack.elementAt(5));
    while (!stack.empty())
      System.out.println(stack.pop());
  }
}
  

The output:


stack = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
element 5 = 5
java 2s.com
9
8
7
6
5
4
3
2
1
0
Home 
  Java Book 
    Collection