CHAPTER 21: The Package java.util Previous
Previous
Java Language
Java Language
Index
Index
Next
Next

21.12 The Class java.util.Stack

21.12.1 push , 21.12.2 pop , 21.12.3 peek , 21.12.4 empty , 21.12.5 search

The class Stack extends 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.

public class Stack extends Vector {
	public Object push(Object item);
	public Object pop() throws EmptyStackException;
	public Object peek() throws EmptyStackException;
	public boolean empty();
	public int search(Object o);
}

When a stack is first created, it contains no items.


21.12.1 push

public Object push(Object item)

The item is pushed onto the top of this stack. This has exactly the same effect as:

addElement(item)

See method addElement of Vector (S21.11.13).


21.12.2 pop

public Object pop() throws EmptyStackException

If the stack is empty, an EmptyStackException is thrown. Otherwise, the topmost item (last item of the Vector) is removed and returned.


21.12.3 peek

public Object peek() throws EmptyStackException

If the stack is empty, an EmptyStackException is thrown. Otherwise, the topmost item (last item of the Vector) is returned but not removed.


21.12.4 empty

public boolean empty()

The result is true if and only if the stack contains no items.


21.12.5 search

public int search(Object o)

If the object o occurs as an item in this Stack, this method returns the distance from the top of the stack of the occurrence nearest the top of the stack; the topmost item on the stack is considered to be at distance 1. The equals method (S20.1.3) is used to compare o to the items in this Stack.

Top© 1996 Sun Microsystems, Inc. All rights reserved.