Java Snippet

ArrayList vs LinkedList Cheat Sheet

Difficulty: Easy

`ArrayList` and `LinkedList` both implement `List`, but their performance profiles are nearly opposite. This snippet shows the basic operations on each, the cases where `LinkedList` actually wins (head/tail mutation via the `Deque` API), and a quick benchmark that demonstrates random access cost. The takeaway: default to `ArrayList`; only reach for `LinkedList` when you genuinely need queue or deque behaviour.

Code Snippets
/

ArrayList vs LinkedList Cheat Sheet

ArrayList vs LinkedList Cheat Sheet

`ArrayList` and `LinkedList` both implement `List`, but their performance profiles are nearly opposite. This snippet shows the basic operations on each, the cases where `LinkedList` actually wins (head/tail mutation via the `Deque` API), and a quick benchmark that demonstrates random access cost. The takeaway: default to `ArrayList`; only reach for `LinkedList` when you genuinely need queue or deque behaviour.

Java
Easy
3 snippets
java-collections
data-structures
comparison

345 views

8

ArrayList is a resizing array: add(E) is amortised O(1), get(i) is O(1), and iteration is cache-friendly because elements are contiguous in memory. add(i, E) and remove(i) are O(n) because the tail must shift, but you rarely insert in the middle, so this is not a real bottleneck. Use ArrayList for almost everything: returning collections from methods, building up results in a loop, accumulating filtered values. The default capacity is 10 but it doubles on demand, so pre-sizing with new ArrayList<>(expected) saves reallocations only on hot paths.