๐ 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 |