Tech

How to Use Stacks in Java



The Java Stack class extends the Vector class. It lets you create new elements, view an element in the stack, update an element in the stack, and delete all elements from the stack. Stacks process data in a first-in-last-out (FILO) order. This means you can only add or remove items from the top of a stack.

The stack data structure has five primary methods. However, the Java Stack class also has access to over 40 other methods, which it inherits from the Vector class.


Creating a Stack in Java

The Stack class has a single constructor that allows you to create an empty stack. Each Stack has a type argument, which dictates the type of data it will store.

import java.util.Stack;

public class Main {
public static void main(String[] args) {
Stack<String> Customers = new Stack<String>();
}
}

The code above creates a Stack data structure called Customers that stores String values.

Populating a Stack

One of the Stack class’s five primary methods is the push() method. It takes a single item that has the same data type as the Stack and pushes that item to the top of the Stack.


Customers.push("Jane Doe");
Customers.push("John Doe");
Customers.push("Patrick Williams");
Customers.push("Paul Smith");
Customers.push("Erick Rowe");
Customers.push("Ella Jones");
Customers.push("Jessica Brown");

The code above populates the Customers’ Stack with seven items. It pushes each new item to the top of the Stack. So, the item at the top of the Customers Stack is Jessica Brown. And you can confirm this using the Stack peek() method. The peek() method takes no arguments. It returns the object at the top of the Stack without removing it.


System.out.println(Customers.peek());

The code above returns the following output to the console:

Jessica Brown

View the Items in a Stack

The stack data structure is quite restrictive in how it allows you to interact with its data. You should mainly use a Stack via its topmost item. However, you can also use methods inherited from the Vector class to access arbitrary elements. Such methods include elementAt and removeElementAt.

The easiest way to get an overview of a Stack’s contents is simply to print it. Pass a Stack object to System.out.println and the Stack’s toString() method will produce a nice summary:


System.out.println(Customers);

The code above prints the following output to the console:

[Jane Doe, John Doe, Patrick Williams, Paul Smith, Erick Rowe, Ella Jones, Jessica Brown]

Searching for an Item Position in a Stack

If you know an item in the Stack, you can identify its index position or its position relative to the top of the Stack. The indexOf() method takes an item in the Stack and returns its index position. Be mindful that a Stack starts indexing its items at zero.


System.out.println(Customers.indexOf("Jane Doe"));

The code above prints the following output to the console:

0

The search() method is one of the Stack class’s primary methods. It returns an item position relative to the top of the stack, where the item at the top of the Stack has position number one.

System.out.println(Customers.search("Jane Doe"));

The code above prints the following output to the console:

7

If you supply the search() or the indexOf() methods with an item that is not in the Stack, they will return a negative one.

System.out.println(Customers.search("Elsa Doe"));
System.out.println(Customers.indexOf("Elsa Doe"));

The code above prints the following output to the console:

-1
-1

Updating Items in a Stack

You can only manipulate an item at the top of a Stack. So, if you want to update an element that is not at the top of the Stack, you will have to pop all the items above it. The pop() method is one of the Stack’s primary methods. The pop() method takes no arguments. It removes the item at the top of the stack and returns it.



Customers.pop();
Customers.pop();
Customers.push("Ella James");
Customers.push("Jessica Brown");
System.out.println(Customers);

The code above prints the following output to the console:

[Jane Doe, John Doe, Patrick Williams, Paul Smith, Erick Rowe, Ella James, Jessica Brown]

As you can see from the output, the code updates Ella’s surname to James. It involves a process that pops items from the stack until you arrive at the target object. It then pops the target object; updates it; and pushes it, along with the items that were on top of the target item, back to the stack. You will have to use a program that performs operations like the one above, each time you wish to update an item in your Stack.

Deleting an Item From a Stack

To delete a single item from the Stack data structure, you can again use the pop() method. If the item you want to delete is not at the top, you can pop items at the top until you reach the desired one.

Deleting All the Items in a Stack

To delete all the elements from a Stack, you can use a Java while loop with the pop() method to delete the elements one at a time. A more efficient approach, however, is to use the clear() method. The clear() method is one that the Stack class inherits from the Vector class. It takes no arguments, returns nothing, but simply removes all the elements within the Stack data structure.


Customers.clear();
System.out.println(Customers.empty());

The code above deletes all the items in the Customers Stack. It then uses the empty() method to check if the Stack is empty. The empty() is another primary method of the Java Stack Class. It takes no arguments and returns a Boolean value. This method returns true if the Stack is empty and false otherwise.

The code above prints the following output to the console:

true

Practical Applications for the Stack Data Structure

The Stack data structure is very restrictive. It does not provide as much flexibility in data processing as other data structures. This begs the question: when should you use the Stack data structure?

The Stack data structure is an ideal fit for applications that require data processing in reverse order. These include:

  • An application that checks if a word is a palindrome.
  • An application that converts decimal numbers into binary numbers.
  • Applications that allow users to undo.
  • Games that allow a user to go back to previous moves, such as a chess game.

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button