Card 01/ 08
All 8 cards
ConceptDifficulty: Intermediate1 min
Two Lists With the Same Methods and Opposite Costs
Two classes implement List. They have the same methods, take the same arguments and return the same things, and swapping one for the other can turn a report that runs in a second into one that runs in a minute.
The difference is how they store what you give them.
| 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. Each is faster at the thing the other is slow at, and which of those two things your code does is not visible in the interface at all.
So this is the clearest case in the library for choosing on cost rather than on API. The methods will not tell you anything, because they are identical by design.
- Java
- Java Collections
- Performance