The Stack class is found in java.util and it extends the Vector Class. This means it can grow and shrink as needed, which is helpful for a Stack.
As it extends a Vector, it is helpful to Parameterize the constructor.
Stack<String> stack = new Stack<String>();
Just like the Stack that we’ve created, it has the same methods: push(), pop(), and peek(). It also has several methods such as empty() which are optional, and a search() method. Some additional methods exist because it is inherited from the Vector class. That means things like capacity(), get(), and other methods exist and will work. While this will frustrate purists, it shouldn’t get in the way of you from using this class.
public static void main(String args[]) {
Stack<String> stack = new Stack<String>();
stack.push("Hello");
stack.push("World");
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.peek());
stack.pop();
stack.pop(); // should throw an exception
}
Notice how we use the standard functions for a stack, and if you are using a stack class, you should limit yourself to the methods that are relevant to a stack, otherwise, you are using a Stack in name only.
In this example, you might notice how we have one more pop than push. While this would normally come from an external source, we want to show what will happen if you pop from an empty stack. In Java, it will throw an exception – specifically the java.util.EmptyStackException
exception. So we need to either put pop method calls in a try catch, or have some other method to ensure you don’t pop from an empty stack.
Java Stacks was originally found on Access 2 Learn