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:
- CPU Cache Locality (L1/L2/L3): Because
ArrayListstores references in a contiguous block of memory, the CPU hardware prefetcher loads sequential elements into ultra-fast CPU cache lines (64 bytes).LinkedListallocates node objects randomly on the heap, resulting in constant CPU cache misses (pointer chasing). - Memory Overhead: Each node in
LinkedListconsumes 24 bytes of object overhead plus two 8-byte pointers (32 bytes total per node) just to hold a single 8-byte reference.ArrayListhas 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().