Phase 16 of 20 · Topic 16.1

List Interface: ArrayList vs LinkedList

1Concept

ArrayList is backed by a dynamically resizing array (`oldCapacity + (oldCapacity >> 1)` = 1.5x growth), offering O(1) random access and excellent CPU cache locality. LinkedList is a doubly-linked list with O(1) insertion/deletion at ends, but poor memory efficiency due to 24-byte Node pointer overhead per element and cache misses during traversal.

2Architecture Diagram

ArrayList:   [ 0x01 | 0x02 | 0x03 | 0x04 ] (Contiguous Heap Array - O(1) Random Access)
LinkedList:  [Node A] <---> [Node B] <---> [Node C] (Fragmented Heap Pointers - O(N) Traversal)

3Code Example

Core Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListComparisonDemo {
    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>(10); // Pre-allocated capacity
        List<String> linkedList = new LinkedList<>();

        arrayList.add("PostgreSQL");
        arrayList.add("Redis");
        arrayList.add("Kafka");

        // O(1) Random Access via Array Index
        String item = arrayList.get(1);
        System.out.println("ArrayList O(1) Index Lookup: " + item);

        linkedList.addFirst("Job-Queue-Head");
        System.out.println("LinkedList Head Element: " + linkedList.get(0));
    }
}

4Expected Output

ArrayList O(1) Index Lookup: Redis
LinkedList Head Element: Job-Queue-Head

5Key Takeaways

  • Prefer ArrayList over LinkedList in virtually all production scenarios.
  • Always initialize ArrayList with expected size (`new ArrayList<>(capacity)`) to avoid internal array resizing.
  • LinkedList consumes significantly more memory (24 bytes per node on 64-bit JVMs with compressed OOPs).