“ArrayList or LinkedList?” is a classic Java interview question. The short answer is “almost always ArrayList”, but interviewers want to hear why.
How ArrayList works
ArrayList stores elements in an internal array. Reading list.get(500) jumps straight to position 500, so access by index is very fast. Adding at the end is usually fast too; when the array is full, Java creates a bigger one and copies the elements across, but this happens rarely enough that adding is still efficient on average.
The cost comes when you insert or remove in the middle: every element after that position must shift.
How LinkedList works
LinkedList stores each element in a separate node that points to the previous and next nodes. Inserting or removing is cheap once you are at the right node, because only a few links change. But reaching position 500 means walking through 500 nodes, so get(index) is slow.
The comparison
- Access by index: ArrayList fast, LinkedList slow.
- Add at the end: both fast.
- Insert or remove in the middle: ArrayList must shift elements; LinkedList must first walk to the position, so in practice it is often not faster.
- Memory: LinkedList uses more, because every node stores two extra references.
Which to choose
Use ArrayList by default. Modern CPUs read arrays very efficiently, so ArrayList wins in most real programs. If you need a queue or stack, prefer ArrayDeque over LinkedList.
Follow-up questions to prepare
- What is the default capacity of an ArrayList, and what happens when it grows?
- Is ArrayList thread-safe? (No. Use
Collections.synchronizedListorCopyOnWriteArrayListwhen needed.) - What is the difference between
List,SetandMap?
Related: Java collections: List, Set and Map and how a Java HashMap works.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
