Junior
Which collection in Java implements the discipline of Last In, First Out (LIFO)?
sobes.tech AI
Answer from AI
java.util.Stack.
It is a subclass of Vector. Main methods:
push(E item): adds an element to the top of the stack.pop(): removes and returns the element from the top of the stack.peek(): returns the element at the top of the stack without removing it.empty(): checks if the stack is empty.search(Object o): returns the 1-based position of the first occurrence of the element.
Example of usage:
import java.util.Stack;
// Creating a stack
Stack<String> stack = new Stack<>();
// Adding elements (push)
stack.push("Element 1");
stack.push("Element 2");
stack.push("Element 3");
// Checking the top (peek)
System.out.println("Top of the stack: " + stack.peek()); // Outputs "Element 3"
// Removing elements (pop)
System.out.println("Popped element: " + stack.pop()); // Outputs "Element 3"
System.out.println("Popped element: " + stack.pop()); // Outputs "Element 2"
// Checking if empty (empty)
System.out.println("Is the stack empty? " + stack.empty()); // Outputs "false"
// Removing the last element
System.out.println("Popped element: " + stack.pop()); // Outputs "Element 1"
// Checking if empty after removing all elements
System.out.println("Is the stack empty? " + stack.empty()); // Outputs "true"
Note that the official Java documentation recommends using Deque (e.g., ArrayDeque) as a preferred alternative to Stack for stack implementation, because Stack is an older class from earlier Java versions and does not fully support the List interface. However, Stack still follows the FILO discipline.
Example using ArrayDeque as a stack:
import java.util.Deque;
import java.util.ArrayDeque;
// Creating a Deque to use as a stack
Deque<String> stackDeque = new ArrayDeque<>();
// Adding elements (push)
stackDeque.push("Element A");
stackDeque.push("Element B");
stackDeque.push("Element C");
// Checking the top (peek)
System.out.println("Top of the stack (Deque): " + stackDeque.peek()); // Outputs "Element C"
// Removing elements (pop)
System.out.println("Popped element (Deque): " + stackDeque.pop()); // Outputs "Element C"
System.out.println("Popped element (Deque): " + stackDeque.pop()); // Outputs "Element B"
Methods push, pop, and peek in Deque are equivalent to the corresponding methods in Stack when used as a stack.