Java Collection Framework provides a Stack class that implements a Stack data structure based on the last-in-first-out principle. The class provides basic push and pop operations, as well as three additional functions: empty, search, and peek. It can be considered as a subclass of Vector and extends it with the five mentioned functions.
It's important to note that the Stack class in Java is a legacy class and inherits from Vector in Java. Although it's thread-safe, it involves overhead when we don't need thread safety. Thus, it's recommended to use ArrayDeque for stack implementation as it's more efficient in a single-threaded environment.
Here's an example implementation of Stack using ArrayDeque:
import java.util.ArrayDeque; public class StackExample { public static void main(String[] args) { ArrayDeque<Integer> stack = new ArrayDeque<>(); stack.push(10); stack.push(20); stack.push(30); System.out.println(stack.peek()); System.out.println(stack.pop()); System.out.println(stack.peek()); } }
The output of the above code is:
30
30
20
Another example implementation of Stack using ArrayDeque to demonstrate its size and empty functions:
import java.util.ArrayDeque; public class StackExample { public static void main(String[] args) { ArrayDeque<Integer> stack = new ArrayDeque<>(); stack.push(10); stack.push(20); stack.push(30); System.out.println(stack.size()); System.out.println(stack.isEmpty()); } }
The output of the above code is:
3 false
The Stack class in Java provides the following methods:
In conclusion, the Stack class in Java provides a simple and efficient way of implementing the stack data structure in Java. However, it's important to note that it's a legacy class and might not be the best choice in certain scenarios. Using ArrayDeque instead can provide a more efficient solution in a single-threaded environment.