Skip to main content
InterviewHubPRO
Section Overview
Q11

Question 11 of 50

Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

22%
Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

What is the difference between ArrayList and LinkedList, and why is ArrayList almost always preferred?

senior LevelCode ExampleSystem DesignData Structures

In Simple Words:

  • ArrayList is backed by a contiguous, resizable array. It provides $O(1)$ constant-time random access by index via direct memory pointer arithmetic.
  • LinkedList is a doubly linked list where each element is an independent object node holding references to the previous and next nodes. It provides $O(1)$ insertion at head/tail but $O(N)$ traversal for any indexed access.

Why ArrayList Outperforms LinkedList in Practice:

  1. CPU Cache Locality (L1/L2/L3): Because ArrayList stores references in a contiguous block of memory, the CPU hardware prefetcher loads sequential elements into ultra-fast CPU cache lines (64 bytes). LinkedList allocates node objects randomly on the heap, resulting in constant CPU cache misses (pointer chasing).
  2. Memory Overhead: Each node in LinkedList consumes 24 bytes of object overhead plus two 8-byte pointers (32 bytes total per node) just to hold a single 8-byte reference. ArrayList has zero per-element object overhead.
java
List<String> arrayList = new ArrayList<>(1000); // Pre-allocated contiguous memory
List<String> linkedList = new LinkedList<>();    // Dispersed heap nodes

// Benchmark insight: Even for middle insertions, copying contiguous memory via System.arraycopy()
// in ArrayList is typically faster than traversing scattered nodes in LinkedList!

Under the Hood:

When ArrayList exceeds capacity, it grows by 50% (newCapacity = oldCapacity + (oldCapacity >> 1)) and invokes Arrays.copyOf() which delegates to the native CPU instruction memmove via System.arraycopy().