Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

492 Part II: The Java Library


the stack. Here is an example that creates a stack, pushes severalIntegerobjects onto it, and
then pops them off again:

// Demonstrate the Stack class.
import java.util.*;

class StackDemo {
static void showpush(Stack<Integer> st, int a) {
st.push(a);
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}

static void showpop(Stack<Integer> st) {
System.out.print("pop -> ");
Integer a = st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}

public static void main(String args[]) {
Stack<Integer> st = new Stack<Integer>();

System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);

try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}

Method Description
boolean empty( ) Returnstrueif the stack is empty, and returnsfalseif the stack
contains elements.
E peek( ) Returns the element on the top of the stack, but does not remove it.
E pop( ) Returns the element on the top of the stack, removing it in the
process.
E push(Eelement) Pusheselementonto the stack.elementis also returned.
int search(Objectelement) Searches forelementin the stack. If found, its offset from the top
of the stack is returned. Other wise, –1 is returned.

TABLE 17-16 The Methods Defined byStack
Free download pdf