Java Stack 101: Delving into the Stack Class

Published in the Java Developer group
The Stack in Java is a data structure, much like a queue, array, linked list, or tree. Where it differs from the others is that the Java Stack is based on the Last In, First Out (LIFO) principle. What this means is that when you use the two commands to add and remove an element from the stack, the first one you remove will always be the last one you added. Java Stack 101: Delving into the Stack Class - 1Let’s take a closer look at the Java Stack Class

Exploring the Java Stack Class

The Java Stack Class is an extension of the Vector class, which itself extends the List class. Because vectors are mutable and can grow and shrink with the demands of the elements inside, Stacks can also change sizes on demand. The extension of the Vector class adds five operations that transform a Vector into a Stack. These five operations are:
  • .push(E item) – places an element onto the top of the stack
  • .pop() – removes the element at the top of the stack and returns it as the value of the function
  • .peek() – looks at the element at the top of the stack without removing it
  • .empty() – Boolean function to test if the stack is empty or not. Returns a 0 or 1.
  • .search(Object o) – Looks for o and returns its position. The value is 1-based, not 0-based
Stack also inherits all of the methods that are part of Vector, including but not limited to, toString(), contains(), indexOf(), and lastElement().

Coding a Java Stack Example

Now that we know the functions for the Stack, let’s code a java stack example. Stacks are very useful for handling data that must be stored temporarily and retrieved quickly. Because the Stack is LIFO, it’s exceptionally useful for node traversal when exploring a tree data structure. Before we get into all of that, let’s create a basic stack. The code to implement a stack is as follows:

import java.util.*;

class Main {
  public static void main(String[] args) {
    Stack<Integer> stackExample = new Stack<Integer>();
That’s all you need to do to create an empty Stack. You can also just declare it simply without declaring a data type by using:

Stack example = new Stack();
Remember that because Stacks are mutable, as we push elements onto the stack, it will automatically adjust in size. Now let’s look at how to use the Stack functions.

Java Stack Implementation

Let’s look at how to use the five methods we explored briefly earlier. Java stack implementation is easy to remember if you think of it as a stack of plates. You put plates onto the stack, but to get a plate, you don’t go to the bottom, you get one from the top. The last one you put on is the first one you take off. Extending our previous example with stackExample, the functions are as follows:

Push


// pushing integers onto the Stack
    stackExample.push(5);
    stackExample.push(10);
At this point, we’re going to show the other functions as if we have pushed these two integers onto the Java stack example every time.

Pop


//popping integers off of the Stack
System.out.println(stackExample.pop());
System.out.println(stackExample.pop());
Output:

10
5

IsEmpty

Now, let’s say that you want to remove all of the elements from a Stack but you aren’t sure how many elements there are. You can combine the Boolean.isEmpty() function with a precondition while loop to pop all of the elements from the Stack. Look at how this java stack implementation is done.

while(!stackExample.isEmpty()) {      
  System.out.println(stackExample.pop());
}
Output

10
5

Peek

We can use .peek() as stack implementation in Java to take a look at the next item on the Stack without removing it.

System.out.println(stackExample.peek());
Output

10
If we pop and print the Stack, it will return 10 and 5 because the 10 is still on the stack. We just looked at it, we did not remove it with the pop function. The peek function is a great tool for Stacks in java.

Search

If we want to find a specific element, the stacks implementation in Java uses .search(e); to find it.

System.out.println(stackExample.search(5));
Output

2
Remember that this is because we count from the top of the Stack and Java Stacks start at 1, not 0 like an Array. So, looking at the stack, it is (10) --> (5), and 5 is in the number 2 spot. If you try to find an element that is not in the Stack, you will get a -1 as an output.

Iterating

When working with any collection, there may be times when you need to look for multiple elements. To save complexity and having to search through the Stack multiple times, you can use iteration. Because Stack in Java extends the List class, there are several options for iterating. One of the easiest is to just use the ListIterator function. ListIterator is nice in that it lets you traverse a Stack from top to bottom or from bottom to top using .hasPrevious() or .hasNext(). Here’s how it looks:

ListIterator<Integer> exampleIterator = stackExample.listIterator(stackExample.size());

  while (exampleIterator.hasPrevious()) {
    int iteration = exampleIterator.previous();
    System.out.println(iteration);
  }
Output

10
5
Keep in mind that when you iterate through Stacks in Java, you don’t remove any elements in it. Iterating essentially allows you to peek at every element in the stack in order. When you do this, you can look for locations where certain elements are and then go through and manipulate them. You can count, delete, or even change them if need be.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION