Java collections · Trade-off
ArrayList or LinkedList
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
When would you choose LinkedList over ArrayList? Give me a real case from a backend service.
Then
Follow-ups the interviewer asks next
- What do get(i), add at the end and add in the middle cost for each?
- Isn't inserting in the middle of a LinkedList O(1)?
- How does ArrayList grow, and how do you avoid repeated growth?
- What would you use for a FIFO queue of tasks?
- What did Java 21's getFirst and getLast add?
The answer
What a strong answer covers
- ArrayList: backed by an array. get(i) is O(1); add at the end is amortised O(1) (it grows by about half when full); insert or remove in the middle shifts elements, O(n), but the shift is a fast memory copy.
- LinkedList: doubly linked nodes. get(i) walks the list, O(n); insert is O(1) only once you're already at the node, and getting there is O(n).
- Each LinkedList node is a separate object with two links: several times the memory of an array slot, and poor CPU-cache locality. In practice ArrayList wins almost everywhere.
- Queues and stacks: ArrayDeque (faster than LinkedList, no nulls); between threads, a BlockingQueue.
- Pre-size with
new ArrayList<>(expected)when you know the size. - Java 21 sequenced collections (JEP 431) added getFirst, getLast and reversed to List and others.
The red pen
Common traps
Avoid:"LinkedList is faster for inserts" without the walk cost; using LinkedList as a queue between threads.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.