Using a Stack data structure in Java

problem

You wish to use the Stack in Java. This data structure “stacks” data elements one on top of the other hence its name. Similar to the analogy of plates when we stack one on top of the other. It is also known as a LIFO (Last In First Out) data structure.

SOLUTION

Java’s collection library is giving us out of the box the Stack data structure. This data structure is generic and can easily be used. We will see how to stack a list of Strings representing laundry clothes ready for ironing.

initialize it
StackExample.java
				
					
        Stack<String> laundry = new Stack<>();

				
			

This data structure is generic meaning that can store any type. We specify the type of contents that will store in the “diamond syntax” Stack<String>. It will store only Strings in this case.

adding items
StackExample.java
				
					
        laundry.push("shirt");
        laundry.push("trousers");
        laundry.push("t-shirt");
        laundry.push("hoodie");
        laundry.push("shorts");
        laundry.push("jeans");

				
			

Simply invoke the push() method to insert a new item. Same value can be added more than once.

getting items

To get the last added item we invoke the pop() method. This method also removes it from the data collection.

StackExample.java
				
					String lastAddedItem = laundry.pop();
				
			

lastAddedItem should contain “jeans”

getting the size
StackExample.java
				
					System.out.println(laundry.size());
				
			

This line of code will print the number of elements currently in the Stack.

running

Let’s add all the above code in a main method and invoke it.

StackExample.java
				
					package com.programmerabroad;

import java.util.Stack;

public class StackExample {
    
    public static void main(String[] args) {

        Stack<String> laundry = new Stack<>();

        laundry.push("shirt");
        laundry.push("shirt");
        laundry.push("trousers");
        laundry.push("t-shirt");
        laundry.push("hoodie");
        laundry.push("shorts");
        laundry.push("jeans");
        
        System.out.println(laundry.size());

        String lastAddedItem = laundry.pop();
        System.out.println(lastAddedItem);

        System.out.println(laundry.size());
    }
}

				
			
output

It prints 7 that is the initial number of items.

After the invocation of pop, the last added it’s removed, reducing it’s size by 1.

It prints the “jeans” and then 6 which is the new size.

get item without removing

By using the get(index) method, the item is retrieved and not removed, for example:

StackExample.java
				
					String item = laundry.get(3);
				
			

conclusion

In this post we saw how to initialise, add items and get items from a Stack data structure. This is a LIFO data structure that usually is used when we want to use our data in a Last In First Out fashion. In contrast with FIFO – First In First Out.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.