The Stack class of Java's library   documentation:

  • The Java library contains a generic Stack class:

       java.util.Stack
    

  • How to instantiate Stack objects:

       Stack<Integer> iStack = new Stack<>(); // Integer stack
       Stack<String>  sStack = new Stack<>(); // String stack

  • The Stack class contains the following instance methods:

       boolean empty()
       E       peek()
       E	   push(E item)
       E	   pop()   

Example program using the Stack class in Java's library

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

	// Test Integer stack
        iStack.push(1);
        iStack.push(2);
        iStack.push(3);
        System.out.println( iStack );

        System.out.println( iStack.pop() );
        System.out.println( iStack );

	// Test String stack
        sStack.push("cat");
        sStack.push("dog");
        System.out.println( sStack );

        System.out.println( sStack.pop() );
        System.out.println( sStack );
    } 

Caveat: Java's Stack class is a rogue class...

  • For some unknown reason, the developer of the Stack class made it a subclass of the Vector class:

        java.lang.Object
            java.util.AbstractCollection<E>
                java.util.AbstractList<E>
                    java.util.Vector<E>
                        java.util.Stack<E> 
    

  • The Vector class can access the stored data using an index:

     get(int index)    Returns the element at the specified position
    
     remove(int index) Removes the element at the specified position 
    

  • Since the Stack class is its subclass, it inherits these random access methods...

    • That's why I call it a rogue class - it's not kosher...
    • Because the FIFO behavior is not guaranteed...