Card 01/ 08
ArrayList vs LinkedList: How Each Stores Its Elements
The same methods, and swapping one for the other can turn a one-second report into a one-minute one.
ArrayList and LinkedList both implement List, with the same methods, arguments and results. They differ in how they store elements: an ArrayList keeps them side by side in one array, and a LinkedList keeps each in a separate node that points to the next. That storage decides what each one is fast and slow at.
Swapping one for the other in a report changes no line of its logic, and can turn a report that runs in a second into one that runs in a minute.
| Compared on | ArrayList | LinkedList |
|---|---|---|
| Stores elements in | One array, side by side | Separate nodes, each pointing at the next |
| To find element 500 | Arithmetic on the address | Walk 500 links |
| To insert at the front | Shift every element up one | Change two pointers |
| Memory per element | One slot | The element plus two pointers |
Neither is faster overall. Each is fast at what the other is slow at: an array can jump straight to any position, and a chain of nodes can gain a new link anywhere without moving the others.
So this is the clearest case in the library for choosing on cost rather than on API. The methods tell you nothing, because they are identical by design; which operations your code does most tells you everything.
- Java
- Java Collections
- Performance
← → move through sections and cards