Java Stack class

The stack is a subclass of Vector that implements a standard lifO stack.

The stack defines only the default constructor, which creates an empty stack. In addition to all the methods defined by Vector, the stack also defines some methods of its own.

Stack()
Copy the code

In addition to all the methods defined by Vector, we also define some methods ourselves:

The serial number Methods described
1 Boolean empty() tests whether the stack is empty.
2 Object peek() looks at the Object at the top of the stack, but does not remove it from the stack.
3 Object pop() removes the Object at the top of the stack and returns it as the value of this function.
4 Object push(Object Element) pushes items to the top of the stack.
5 Int Search (Object Element) returns the position of the Object in the stack, base 1.

The instance

The following program illustrates several methods supported by this collection

The instance

import java.util.*;
 
public class StackDemo {
 
    static void showpush(Stack<Integer> st, int a) {
        st.push(new Integer(a));
        System.out.println("push(" + a + ")");
        System.out.println("stack: " + st);
    }
 
    static void showpop(Stack<Integer> st) {
        System.out.print("pop -> ");
        Integer a = (Integer) 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"); }}}Copy the code

The compilation and running results of the above examples are as follows:

stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
Copy the code