ArrayList vs Stack

ArrayList vs Stack

Both ArrayList and Stack are part of Java's java.util package, but they serve different purposes and have distinct characteristics:

1. Hierarchy

  • ArrayList: Implements List interface directly.

  • Stack: Extends Vector, which in turn implements the List interface.


2. Purpose

  • ArrayList: A resizable array that allows dynamic storage of elements. It is used for general-purpose data storage and retrieval.

  • Stack: A subclass of Vector that follows the LIFO (Last In, First Out) principle, where elements are added and removed from the top of the stack.


3. Performance

  • Both ArrayList and Stack allow fast random access due to array-based storage.

  • ArrayList: Better for random access and manipulation of elements.

  • Stack: Optimized for stack operations like push and pop.


4. Thread Safety

  • ArrayList: Not synchronized, so it's faster but requires external synchronization if used in multi-threaded environments.

  • Stack: Synchronized due to being a subclass of Vector. This makes it thread-safe but slower.


5. Methods

  • ArrayList: Provides typical List methods such as get(), add(), remove(), and indexOf().

  • Stack: Provides additional stack-specific methods:

    • push(E item): Adds an element to the top of the stack.

    • pop(): Removes and returns the element at the top.

    • peek(): Returns the element at the top without removing it.

    • empty(): Checks if the stack is empty.

    • search(Object o): Returns the position of an object in the stack.


6. Usage Examples

  • ArrayList

      ArrayList<String> list = new ArrayList<>();
      list.add("A");
      list.add("B");
      System.out.println(list.get(1));
    
  • Stack

      Stack<String> stack = new Stack<>();
      stack.push("A");
      stack.push("B");
      System.out.println(stack.pop());
    

7. When to Use

  • ArrayList: When we need dynamic lists for storing and accessing data efficiently in general-purpose scenarios.

  • Stack: When LIFO operations are explicitly required, like in undo mechanisms, recursion tracking, or expression evaluation.