|
The Stack class implements a Last In, First Out (LIFO)
stack. It extends Vector, and so is a kind of List.
Object
AbstractCollection (implements Collection)
AbstractList (implements List)
AbstractSequentialList
LinkedList
ArrayList
Vector
Stack
AbstractSet (implements Set)
HashSet
TreeSet (implements SortedSet)
AbstractMap (implements Map)
HashMap
TreeMap (implements SortedMap)
WeakHashMap
Dictionary
Hashtable (implements Map)
Properties
Stack adds the following methods beyond what its
super-classes
provide:
package java.util;
public class Stack extends Vector
{
// Constructs an empty stack
public Stack() {}
// Pushes an item onto the stack
public Object push(Object item) {...)
// Pops the top item off the stack
public synchronized Object pop() {...}
// Peeks at the top item on the stack, without removing it.
public synchronized Object peek() {...}
// Returns whether the stack is empty.
public boolean empty() {...}
// Returns the 1-based position where an object is on the stack.
public synchronized int search(Object o) {...}
}
|
Here's an example of the use of a Stack:
package examples;
import java.util.Stack;
public class StackExample
{
public static void main(String[] args)
{
Stack stack = new Stack();
stack.push("Mary");
stack.push("Frank");
stack.push("Joe");
stack.push("Sylvia");
stack.push("Vanessa");
while ( !stack.empty() )
{
String name = (String) stack.pop(); // Note required cast
System.out.println(name);
}
}
}
|
This program outputs the following:
Vanessa
Sylvia
Joe
Frank
Mary
which is in the exact reverse order of the elements pushed onto the
stack.
Note that I've used the empty method, which is in the
JDK 1.1 version of Stack. If I had used the
isEmpty
method, this would have restricted the class to working only under JDK1.2 and
beyond.
|