The Collections Framework gives you ready-made data structures behind three core interfaces: List (ordered, allows duplicates), Set (no duplicates), and Map (key–value pairs). Interviews focus on choosing the right implementation and knowing the performance trade-offs.
The three families and their choices
List: ArrayList (fast random access, slow middle inserts) vs LinkedList (fast inserts/removals, slow random access). Set: HashSet (unordered, O(1)) vs TreeSet (sorted, O(log n)). Map: HashMap (unordered, O(1)) vs TreeMap (sorted keys, O(log n)) vs LinkedHashMap (insertion order).
Using a List and a Map
List<String> names = new ArrayList<>();
names.add("Asha"); names.add("Ravi");
Map<String, Integer> ages = new HashMap<>();
ages.put("Asha", 30);
int a = ages.get("Asha"); // 30 (autounboxed)⚡ The edge
- ArrayList gives O(1) random access but O(n) inserts/removals in the middle; LinkedList is the opposite. Choose by your dominant operation — indexing vs frequent insertion/removal.
- HashMap is unordered with average O(1) lookups; TreeMap keeps keys sorted with O(log n) operations. Use HashMap by default; TreeMap when you need sorted order; LinkedHashMap to preserve insertion order.
Worked example
When would you use ArrayList vs LinkedList?
- ArrayList is backed by a resizable array: fast O(1) get/set by index, but inserting/removing in the middle shifts elements (O(n)).
- LinkedList is a doubly-linked list: O(1) insert/remove at known positions, but O(n) to reach an index.
- Use ArrayList for mostly indexed access (the common case); LinkedList when you insert/remove frequently at the ends/known nodes.
Answer: ArrayList for fast random access; LinkedList for frequent insertions/removals — choose by your dominant operation.
Worked example
What's the difference between a HashSet and a HashMap?
- A HashMap stores key→value pairs and gives O(1) average lookup by key.
- A HashSet stores unique values only (no associated value) and is actually backed by a HashMap internally.
- Use a Map when you need values per key; a Set when you only need membership/uniqueness.
Answer: HashMap stores key→value pairs; HashSet stores unique keys only (and is backed by a HashMap).
⚠ Watch out
- HashMap/HashSet are unordered — don't rely on iteration order; use LinkedHashMap or TreeMap if order matters.
- Modifying a collection while iterating it (without the iterator) throws ConcurrentModificationException.
- Keys/elements in hash collections need correct hashCode() and equals() — custom objects without them misbehave.