🆚 ArrayList
vs LinkedList
– Core Differences
Feature | ArrayList | LinkedList |
---|---|---|
Internal structure | Dynamic array | Doubly linked list |
Access (get/set) | 🔥 Fast (O(1)) | 🐢 Slower (O(n)) |
Insert/Delete at start or middle | 🐌 Slow (O(n)) due to shifting | ⚡ Fast (O(1) at head/tail) |
Memory overhead | Low (array only) | High (nodes + pointers) |
Iteration | Faster due to array locality | Slightly slower |
Thread-safe? | ❌ Not thread-safe (unless synchronized manually) | ❌ Same |
🧠 When to Use Each
✅ Use ArrayList
when:
- You need fast random access using index (
get(i)
) - You mostly add/remove elements at the end
- Memory usage should be optimized
✅ Example:
List<String> cities = new ArrayList<>();
cities.add("Mumbai");
System.out.println(cities.get(0)); // Very fast
✅ Use LinkedList
when:
- You have frequent insertions/deletions at the start, middle, or both ends
- You’re implementing a queue, stack, or deque
- You don’t care much about random access performance
✅ Example:
Queue<String> tasks = new LinkedList<>();
tasks.add("Task 1");
tasks.remove(); // Fast removal at head
🧑💼 Interview-Ready Takeaways
Question | Key Points |
---|---|
Which is faster for search? | ArrayList —because of direct index access |
Which is better for adding/removing in middle? | LinkedList —no shifting elements |
Can you use both for implementing queues? | Yes—but LinkedList is more natural (supports queue ops) |
When would you avoid using LinkedList? | If memory is critical or you need fast access |