Skip to lesson

Collections interview questions and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Collections interviews test three things: can you choose the right collection, can you predict what tricky code prints, and do you know roughly how the main classes work inside. This review brings the whole Collections section together, with the traps interviewers like most.

Choosing a collection in four questions

When a question says "which collection would you use?", answer these four questions in order. Then name the class and the big-O of the operation the program does most.

  1. Do you look things up by a key, like a roll number or PNR? Yes → a Map. No → go on.
  2. Must duplicates be rejected? Yes → a Set. No → a List or a queue.
  3. Which order do you need? None → Hash…; insertion order → LinkedHash…; sorted or "next after X" → Tree….
  4. Do you only work at the ends? First in, first out or last in, first out → ArrayDeque; always the smallest or most urgent first → PriorityQueue.
Say the trade-off out loud: "TreeMap, because I need sorted keys; that costs O(log n) instead of O(1)." Interviewers listen for the reason, not just the class name.

The classic output traps

Three classic traps in one program: remove(1) on a list of numbers, == on Integer objects, and printing a PriorityQueue.

Example 1 · Three classic output traps in one run

TrickyOutputsDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.PriorityQueue;
public class TrickyOutputsDemo {    public static void main(String[] args) {        List<Integer> rolls = new ArrayList<>(List.of(3, 1, 2));        rolls.remove(1);        System.out.println("After remove(1): " + rolls);        rolls.remove(Integer.valueOf(3));        System.out.println("After remove(Integer.valueOf(3)): " + rolls);
        List<Integer> marks = List.of(127, 127, 128, 128);        System.out.println("127 == 127: " + (marks.get(0) == marks.get(1)));        System.out.println("128 == 128: " + (marks.get(2) == marks.get(3)));        System.out.println("128 equals 128: " + marks.get(2).equals(marks.get(3)));
        PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(50, 30, 40, 10, 20));        System.out.println("PriorityQueue printed: " + pq);        StringBuilder polled = new StringBuilder();        while (!pq.isEmpty()) {            polled.append(pq.poll()).append(" ");        }        System.out.println("PriorityQueue polled:  " + polled.toString().trim());    }}
Output
After remove(1): [3, 2]
After remove(Integer.valueOf(3)): [2]
127 == 127: true
128 == 128: false
128 equals 128: true
PriorityQueue printed: [10, 20, 40, 30, 50]
PriorityQueue polled:  10 20 30 40 50

What this code does

  • remove(1) took out the item at index 1 (the value 1). remove(Integer.valueOf(3)) took out the value 3.
  • The two 127s are the same cached object, but the two 128s are different objects, so == is false while equals is true. The queue prints in heap order, and only poll() gives sorted order.

Most "what does this print?" questions reuse a small set of traps. If a question looks too easy, check for one of these:

  • list.remove(1) removes index 1; list.remove(Integer.valueOf(1)) removes the value 1.
  • == on two Integers compares objects. Values from -128 to 127 are cached and shared, so == happens to work; 128 and above usually gives false. Use equals.
  • Printing a PriorityQueue shows its heap array, not sorted order; only repeated poll() gives sorted order. HashSet, HashMap, Set.of and Map.of have no guaranteed order; Set.of and Map.of can even change between runs.
  • Arrays.asList and List.of look like normal lists but throw on add; a TreeSet whose comparator returns 0 drops items.

Fail-fast iterators

A fail-fast iterator throws ConcurrentModificationException as soon as it sees that the collection was changed behind its back. It stops at once instead of giving wrong results later.

Removing from a list inside a for-each loop fails, except at one lucky position. The first program removes each of four names in turn; the second shows four safe ways.

Example 2 · Fail-fast, and the case that does not fail

FailFastDemo.javaJava
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.List;
public class FailFastDemo {    static void removeWhileLooping(String target) {        List<String> names = new ArrayList<>(List.of("Anil", "Bhanu", "Chitra", "Dinesh"));        try {            for (String n : names) {                if (n.equals(target)) {                    names.remove(n);                }            }            System.out.println("Removed " + target + " quietly: " + names);        } catch (ConcurrentModificationException e) {            System.out.println("Removed " + target + ": " + e.getClass().getSimpleName());        }    }
    public static void main(String[] args) {        removeWhileLooping("Anil");        removeWhileLooping("Bhanu");        removeWhileLooping("Chitra");        removeWhileLooping("Dinesh");    }}
Output
Removed Anil: ConcurrentModificationException
Removed Bhanu: ConcurrentModificationException
Removed Chitra quietly: [Anil, Bhanu, Dinesh]
Removed Dinesh: ConcurrentModificationException

What this code does

  • Removing inside a for-each throws ConcurrentModificationException the next time the loop calls next(), even when the last item is removed.
  • Removing Chitra, the second-to-last item, ends the loop early with no error: hasNext() sees the smaller size and stops. Dinesh is never checked, a silent bug.

Example 3 · Four safe ways to remove while looping

SafeRemovalDemo.javaJava
import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.TreeMap;
public class SafeRemovalDemo {    public static void main(String[] args) {        List<Integer> marks = new ArrayList<>(List.of(78, 22, 91, 30, 64));        Iterator<Integer> it = marks.iterator();        while (it.hasNext()) {            if (it.next() < 35) {                it.remove();            }        }        System.out.println("Iterator.remove: " + marks);
        List<String> orders = new ArrayList<>(List.of("keyboard", "CANCELLED", "mouse", "CANCELLED"));        orders.removeIf(o -> o.equals("CANCELLED"));        System.out.println("removeIf:        " + orders);
        Map<String, Integer> dues = new TreeMap<>(Map.of("Ali", 0, "Bina", 500, "Charan", 0, "Deepa", 1200));        dues.entrySet().removeIf(e -> e.getValue() == 0);        System.out.println("Map removeIf:    " + dues);
        List<String> queue = new ArrayList<>(List.of("P1", "P2", "P3"));        for (String p : new ArrayList<>(queue)) {            if (p.equals("P2")) {                queue.remove(p);            }        }        System.out.println("Loop over copy:  " + queue);    }}
Output
Iterator.remove: [78, 91, 64]
removeIf:        [keyboard, mouse]
Map removeIf:    {Bina=500, Deepa=1200}
Loop over copy:  [P1, P3]

What this code does

  • Iterator.remove() removes through the iterator, so its counter stays in step. removeIf does the loop for you, for lists and for a map's entrySet().
  • Looping over new ArrayList<>(queue) reads a copy, so removing from the real list cannot disturb the loop.

An ArrayList keeps a hidden counter, modCount, that goes up on every add or remove. A for-each loop uses an iterator, which remembers the counter's value at the start. On every next(), it checks the counter; if the list was changed behind its back, it throws ConcurrentModificationException. This is called fail-fast: it stops at once instead of giving wrong results later.

The check happens only in next(). If you remove the second-to-last item, the size drops, hasNext() returns false, and the loop ends quietly, skipping the last item. So no exception does not mean the code is correct. The safe ways are Iterator.remove(), removeIf, map.entrySet().removeIf(...), or looping over a copy.

Inside the main collections, one line each

Interviewers often ask "how does it work inside?". A short, correct line for each class is enough to start, and each one explains the big-O you learned:

  • ArrayList: an array that grows to about 1.5 times its size when full. ArrayDeque: a circular array with a head and a tail index. LinkedList: a chain of nodes linked both ways.
  • HashMap: an array of buckets (16 at first). It doubles when more than 75% full (the load factor 0.75), and a bucket with more than 8 entries becomes a small tree. HashSet is a HashMap that uses only the keys.
  • TreeMap and TreeSet: a red-black tree, a binary search tree that keeps itself balanced, so its height stays O(log n).
  • PriorityQueue: a binary heap stored in an array; the smallest item is always at index 0. LinkedHashMap: a HashMap plus a linked list through its entries, in insertion or access order.

Example 4 · Full example: a store day with five collections

StoreDayDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Comparator;import java.util.Deque;import java.util.List;import java.util.Map;import java.util.PriorityQueue;import java.util.Set;import java.util.TreeMap;import java.util.TreeSet;
record Order(String customer, String item, int price) {}
public class StoreDayDemo {    public static void main(String[] args) {        List<Order> orders = new ArrayList<>();        Deque<Order> undo = new ArrayDeque<>();
        String[][] raw = {                {"Kiran", "Laptop", "55000"}, {"Asha", "Cable", "150"}, {"Kiran", "Cable", "150"},                {"Ravi", "Mouse", "600"}, {"Asha", "Mouse", "600"}, {"Meera", "Cable", "150"},                {"Ravi", "Monitor", "7000"}};        for (String[] r : raw) {            Order o = new Order(r[0], r[1], Integer.parseInt(r[2]));            orders.add(o);            undo.push(o);        }
        Order mistake = undo.pop();        orders.remove(mistake);        System.out.println("Undid: " + mistake.item() + " for " + mistake.customer());
        Map<String, Integer> countByItem = new TreeMap<>();        Map<String, Integer> billByCustomer = new TreeMap<>();        Set<String> customers = new TreeSet<>();        for (Order o : orders) {            countByItem.merge(o.item(), 1, (a, b) -> a + b);            billByCustomer.merge(o.customer(), o.price(), (a, b) -> a + b);            customers.add(o.customer());        }        System.out.println("Items sold: " + countByItem);        System.out.println("Bills: " + billByCustomer);        System.out.println("Customers: " + customers);
        PriorityQueue<Map.Entry<String, Integer>> popular = new PriorityQueue<>(                Comparator.comparing((Map.Entry<String, Integer> e) -> e.getValue()).reversed()                        .thenComparing(e -> e.getKey()));        popular.addAll(countByItem.entrySet());        Map.Entry<String, Integer> top = popular.poll();        System.out.println("Most popular: " + top.getKey() + " (" + top.getValue() + " orders)");    }}
Output
Undid: Monitor for Ravi
Items sold: {Cable=3, Laptop=1, Mouse=2}
Bills: {Asha=750, Kiran=55150, Meera=150, Ravi=600}
Customers: [Asha, Kiran, Meera, Ravi]
Most popular: Cable (3 orders)

What this code does

  • A List keeps every order, an ArrayDeque used as a stack undoes the last one, TreeMaps with merge count items and bills in A to Z order, and a TreeSet lists customers once each.
  • The PriorityQueue orders entries by count, highest first, then by name, so poll() gives the best-selling product: the top-k pattern with k = 1.

Finish up

Mark complete & continue

Next: Student Gradebook