LearnFrenzy
Sign in Take a free test

Java Programming interview · Set 3 of 13

Java Collections Framework

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Why collections decide backend interviews

Interviewers move quickly from “which collection?” to “why?” and then to “what happens under load?”. Know the complexity of the common operations, the equals/hashCode contract and the thread-safe options, and you can answer most of the follow-ups from first principles.

  • InternalsBuckets, hashing, resizing and treeification.
  • ChoosingList, Set, Map and Deque by access pattern.
  • ConcurrencyFail-fast iterators and ConcurrentHashMap.

If there is one Java topic that appears in every backend interview, it is collections. Interviewers use it to check two things at once: whether you know the API, and whether you understand the data structures underneath it. Answer with the trade-off, not just the definition, and you will stand out.

1. How does HashMap work internally?

A HashMap is an array of buckets. When you call put(key, value), Java computes key.hashCode(), spreads the bits, and uses the result to pick a bucket index. If the bucket is empty the entry goes there; if not, the new entry is added to that bucket after checking each existing key with equals().

Since Java 8, a bucket that grows beyond 8 entries (and a table of at least 64 buckets) turns from a linked list into a red-black tree, so a bad hash function degrades lookups to O(log n) instead of O(n). When the number of entries crosses capacity × load factor (16 × 0.75 by default), the table doubles and entries are redistributed.

Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 40);      // hash("pen") → bucket index → stored
stock.put("pen", 35);      // same key: equals() matches, value replaced
System.out.println(stock.get("pen"));   // 35

2. Why must you override hashCode() whenever you override equals()?

The contract says: if two objects are equal by equals(), they must return the same hashCode(). Hash-based collections look in the bucket chosen by the hash first, and only then call equals(). If equal objects produce different hashes, they land in different buckets and the collection never finds the match — you get duplicates in a HashSet and null from a HashMap.

record Employee(int id, String name) { }   // records generate equals() and hashCode() together

Set<Employee> team = new HashSet<>();
team.add(new Employee(7, "Asha"));
team.add(new Employee(7, "Asha"));
System.out.println(team.size());   // 1

3. ArrayList or LinkedList — which would you choose and why?

ArrayList is backed by an array: random access is O(1), appending is amortised O(1), and elements sit next to each other in memory, which the CPU cache loves. LinkedList is a doubly linked list: inserting or removing at a known node is O(1), but finding that node is O(n) and every element carries two extra pointers.

In real projects ArrayList wins almost every time. Pick LinkedList only if you constantly add or remove at both ends — and even then ArrayDeque is usually faster.


4. What is the difference between HashMap, LinkedHashMap and TreeMap?

All three implement Map; the difference is ordering and cost.

  • HashMap — no order, O(1) average for get and put.
  • LinkedHashMap — keeps insertion order (or access order, which makes a neat LRU cache), still O(1).
  • TreeMap — keeps keys sorted using a red-black tree, O(log n), and gives you range methods such as headMap() and ceilingKey().
// A tiny LRU cache with LinkedHashMap (access order + eviction rule)
class LruCache<K, V> extends LinkedHashMap<K, V> {
    private final int max;
    LruCache(int max) { super(16, 0.75f, true); this.max = max; }
    @Override protected boolean removeEldestEntry(Map.Entry<K, V> e) { return size() > max; }
}

5. What does fail-fast mean? How do you remove items while iterating?

Iterators of ArrayList, HashMap and most collections are fail-fast: they track a modification count, and if the collection changes structurally during iteration (other than through the iterator itself) they throw ConcurrentModificationException. Remove safely with Iterator.remove() or, more simply, removeIf().

List<Integer> marks = new ArrayList<>(List.of(35, 72, 18, 90));
// for (Integer m : marks) if (m < 40) marks.remove(m);   // ConcurrentModificationException
marks.removeIf(m -> m < 40);
System.out.println(marks);   // [72, 90]

6. How is ConcurrentHashMap different from a synchronised HashMap?

Collections.synchronizedMap() wraps every method in one lock, so only one thread can use the map at a time. ConcurrentHashMap locks at bucket level for writes (using CAS for empty buckets) and lets reads proceed without locking, so many threads work in parallel. It also offers atomic compound operations — putIfAbsent, compute, merge — which avoid the classic check-then-act race. Note that it does not allow null keys or values.

ConcurrentHashMap<String, Integer> hits = new ConcurrentHashMap<>();
// safe even when many threads count at the same time
hits.merge("/home", 1, Integer::sum);

7. Comparable vs Comparator — when do you use each?

Comparable defines the natural order inside the class itself (compareTo), for example sorting employees by id. Comparator defines an external order you can swap at the call site — by salary, then by name. With Java 8 comparators read almost like English.

employees.sort(Comparator.comparing(Employee::salary).reversed()
                         .thenComparing(Employee::name));

8. What is the difference between List.of() and Arrays.asList()?

List.of() (Java 9+) returns a truly immutable list: any add, remove or set throws UnsupportedOperationException, and it rejects null. Arrays.asList() returns a fixed-size view backed by the array: you cannot add or remove, but you can call set(), and that change writes through to the original array.


Remember

Key points

  • equals() and hashCode() travel together

    Equal objects must share a hash code, or hash collections break silently.

  • Default to ArrayList and HashMap

    Switch only when you need ordering, sorting or a deque.

  • Treeified buckets

    Since Java 8 a crowded bucket becomes a red-black tree: O(log n) worst case.

  • Use removeIf()

    Never remove from a collection inside a for-each loop.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What happens if you use a mutable object as a HashMap key and change it after inserting? Intermediate

    Its hash code changes, so a lookup searches a different bucket and the entry becomes unreachable — a memory leak that is hard to spot. Use immutable keys such as String, wrapper types or records.

    Key insight: Keys should be immutable.

  2. 2 Why is the default load factor 0.75? Intermediate

    It balances memory and speed. A lower factor wastes space; a higher one means more collisions and longer bucket chains before resizing.

  3. 3 Can HashMap store a null key? Basic

    Yes, one null key (it always goes to bucket 0) and any number of null values. Hashtable and ConcurrentHashMap allow neither.

  4. 4 How would you make a collection read-only before returning it from a method? Basic

    Return List.copyOf(list) for an immutable snapshot, or Collections.unmodifiableList(list) for a read-only view that still reflects later changes to the original.

    public List<Order> orders() {
        return List.copyOf(orders);   // callers cannot modify our state
    }
  5. 5 Why can iteration over a HashSet print elements in a different order on another JVM? Advanced

    Order depends on hash values and table capacity, which are implementation details. Never depend on it; use LinkedHashSet for insertion order or TreeSet for sorted order.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links