Learn how Java Vector and Java Stack work, their differences, and practical usage in Java programming.
Java Vector is a dynamic array that can grow or shrink in size. It is part of the Java Collection Framework and is synchronized, making it thread-safe.
Java Vector allows dynamic storage of elements, thread-safe operations, and provides standard methods for adding, removing, and accessing elements.
Vector resizes dynamically, is synchronized for thread safety, and integrates easily with Collection methods.
Vector is slower than ArrayList due to synchronization overhead and is considered a legacy class in modern applications.
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector vec = new Vector<>();
vec.add("Apple");
vec.add("Banana");
vec.add("Orange");
System.out.println("Vector elements: " + vec);
vec.remove("Banana");
System.out.println("After removal: " + vec);
}
}
Java Stack is a collection class representing a last-in-first-out (LIFO) stack of objects. It extends Vector and provides operations like push, pop, and peek.
Java Stack allows elements to be stored in LIFO order, supports push/pop/peek operations, and provides easy access to the top element.
Stack provides LIFO behavior suitable for undo mechanisms, parsing expressions, and is thread-safe because it inherits synchronization from Vector.
Stack is slower than non-synchronized collections and limited to LIFO operations.
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Stack elements: " + stack);
System.out.println("Top element: " + stack.peek());
stack.pop();
System.out.println("After pop: " + stack);
}
}
| Aspect | Java Vector | Java Stack |
|---|---|---|
| Data Structure | Dynamic array | LIFO Stack |
| Inheritance | Extends AbstractList | Extends Vector |
| Operations | Add, remove, get elements | Push, pop, peek |
| Thread-safety | Synchronized | Synchronized (inherited from Vector) |