ArrayList vs LinkedList in Java
Java’s Collections Framework provides two commonly used List implementations: ArrayList and LinkedList. While both implement the List interface, they differ in their underlying data structures, performance, and use cases. Let’s break down their differences with examples and diagrams.
1. Underlying Structure
- ArrayList → Backed by a dynamic array. Elements are stored in contiguous memory.
- LinkedList → Implemented as a doubly-linked list. Each node stores data + pointers to the previous and next node.
Diagram:
ArrayList (Dynamic Array) [ 0 ] → [ 1 ] → [ 2 ] → [ 3 ] → [ 4 ] (index based access)
LinkedList (Doubly Linked Nodes) NULL ← [0 | *] ↔ [1 | *] ↔ [2 | *] ↔ [3 | *] → NULL
2. Code Example
ArrayList Example:
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
// Random access is fast
System.out.println("Element at index 1: " + list.get(1));
}
}
LinkedList Example:
import java.util.*;
public class LinkedListExample {
public static void main(String[] args) {
List list = new LinkedList<>();
list.add("Java");
list.add("Python");
list.add("C++");
// Insertion at the beginning is efficient
list.add(0, "Go");
System.out.println("First Element: " + list.get(0));
}
}
3. Performance Comparison
| Operation | ArrayList | LinkedList |
|---|---|---|
| Random Access (get) | O(1) ✅ | O(n) ❌ |
| Insertion / Deletion at end | O(1) (Amortized) | O(1) |
| Insertion / Deletion in middle | O(n) | O(n) (but O(1) if iterator used) |
| Memory Usage | Less overhead | More overhead (extra node pointers) |
4. When to Use What?
- Use ArrayList when you need fast random access and memory efficiency.
- Use LinkedList when your application requires frequent insertions and deletions in the middle or at ends.
Rule of Thumb: If you’re unsure, start with ArrayList. It is generally faster and more commonly used in real-world applications.
5. Quick Benchmark (Conceptual)
ArrayList get(index): O(1) → very fast LinkedList get(index): O(n) → slower as size grows Example with 1M elements: - ArrayList get(500000) ≈ nanoseconds - LinkedList get(500000) ≈ milliseconds
Conclusion
Both ArrayList and LinkedList have their place in Java development. However, due to cache locality, memory efficiency, and overall speed, developers tend to prefer ArrayList in most scenarios. Reach for LinkedList only if your problem domain specifically benefits from frequent insert/delete operations in the middle of the list.
Comments
Post a Comment