Curriculum
In Java, Stack
is a class that implements a last-in, first-out (LIFO) data structure, which means that the last element added to the stack will be the first one to be removed. The Stack
class provides a set of methods to add, remove, and access elements in the stack. In this answer, I will explain how to create and use a Stack
in Java, as well as some of its commonly used methods.
To use Stack
in Java, you must first import the java.util.Stack
class. You can create a Stack
in Java using the following code:
Stack<String> stack = new Stack<>();
In the above example, we create a new Stack
that can hold elements of type String
.
Once a Stack
has been created, elements can be added or removed from it using the following methods:
// Add an element to the top of the Stack stack.push("apple"); // Remove and return the top element of the Stack String top = stack.pop(); // Return the top element of the Stack without removing it top = stack.peek(); // Remove all elements from the Stack stack.clear();
Stack
provides several methods to access elements in the stack:
// Get the index of the first occurrence of an element int index = stack.search("banana"); // Get the size of the Stack int size = stack.size();
Some other commonly used methods provided by the Stack
class include:
// Check if the Stack is empty boolean isEmpty = stack.empty(); // Convert the Stack to an array String[] array = stack.toArray(new String[0]); // Iterate over the elements in the Stack using a for-each loop for (String element : stack) { System.out.println(element); }
One thing to keep in mind when using Stack
is that it is a legacy class, which means that it is not recommended to use it in new code. Instead, it is recommended to use the Deque
interface, which provides a similar set of methods and is more flexible.