Stack Data Structure Overview
Stack represents a fundamental data structure following the Last-In-First-Out (LIFO) principle. In Java's collection framework, the Stack class extends Vector, leveraging its underlying array-based implementation.
Core Characteristics
- LIFO (Last-In-First-Out) element access pattern
- Extends Vector class, inheriting array-based storage
- Thread-safe operations through synchronized methods
Class Structure
public class Stack<E> extends Vector<E> {
private static final long serialVersionUID = 1224463164541339165L;
}
Key Method Implementations
Element Insertion
public E push(E element) {
addElement(element);
return element;
}
The push operation delegates to Vector's addElement method, which handles capacity management and thread synchronization.
Element Removal
public synchronized E pop() {
int currentSize = size();
E topElement = peek();
removeElementAt(currentSize - 1);
return topElement;
}
Pop retrieves the top element using peek() and removes it from the underlying array.
Top Element Access
public synchronized E peek() {
int currentSize = size();
if (currentSize == 0)
throw new EmptyStackException();
return elementAt(currentSize - 1);
}
Empty Check
public boolean empty() {
return size() == 0;
}
Element Search
public synchronized int search(Object target) {
int lastIndex = lastIndexOf(target);
if (lastIndex >= 0) {
return size() - lastIndex;
}
return -1;
}
The search method returns the position from the top of the stack, with 1 indicating the top element.
Implementation Notes
Stack utilizes Vector's internal data structure:
protected Object[] elementData;
protected int elementCount;
All stack operations manipulate this underlying array, with Vector handling synchronization and capacity management. The array-based implementation provides effciient random access while maintaining LIFO semantics through controlled insertion and removal at the array's end.