BhauAutomation

Java Vector & Java Stack

Learn how Java Vector and Java Stack work, their differences, and practical usage in Java programming.

What is Java Vector?

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.

Objectives of Java Vector

Java Vector allows dynamic storage of elements, thread-safe operations, and provides standard methods for adding, removing, and accessing elements.

Advantages

Vector resizes dynamically, is synchronized for thread safety, and integrates easily with Collection methods.

Limitations

Vector is slower than ArrayList due to synchronization overhead and is considered a legacy class in modern applications.

Example of Java Vector

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);
    }
}
  

What is Java Stack?

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.

Objectives of Java Stack

Java Stack allows elements to be stored in LIFO order, supports push/pop/peek operations, and provides easy access to the top element.

Advantages

Stack provides LIFO behavior suitable for undo mechanisms, parsing expressions, and is thread-safe because it inherits synchronization from Vector.

Limitations

Stack is slower than non-synchronized collections and limited to LIFO operations.

Example of Java Stack

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);
    }
}
  

Difference Between Java Vector & Java 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)