Java Collections Interview Questions: HashMap, ArrayList, TreeMap and Iterators

Reviewed by Mark Dickie · Last updated

5 questions on this page you can answer and see marked on the spot. Go to the first one

Java collections are the interfaces and classes in java.util that hold, order, and search groups of objects. Interviewers mostly test which implementation fits which job, how HashMap and ArrayList behave internally, and where iteration and equality go wrong. Be ready to name the cost of each common operation and the failure mode it hides. Most answers come back to the hashCode and equals contract, resizing, and fail-fast iterators.

Which Java collections choices do interviewers test?

Compare each pair by its cost or its failure mode, not just the class name.

TopicWhat to be able to say
HashMapKeys map to buckets by hash. The table resizes when it passes a 0.75 load factor, doubling capacity, and long buckets treeify from Java 8 on.
ArrayList vs LinkedListArrayList get(i) is O(1) over a backing array. LinkedList add or remove through an iterator is O(1), but get(i) walks the chain.
TreeMapA red-black tree keeps keys sorted, so get, put, and remove are O(log n) and iteration follows key order.
Fail-fast iteratorsA modCount check throws ConcurrentModificationException during a for-each loop. Iterator.remove() is the safe removal path.
hashCode and equalsOverriding equals without hashCode makes HashSet and HashMap lookups miss objects that look equal.
List.of vs Collections.unmodifiableListList.of rejects nulls and cannot change. unmodifiableList is a read-only view, so changes to the backing list still show through.

Practise these by running them, not only by reading about them:

  1. Build an LRU cache on LinkedHashMap with accessOrder set to true, overriding removeEldestEntry.
  2. Remove items from an ArrayList inside a for-each loop, catch the ConcurrentModificationException, then redo it with Iterator.remove().
  3. Put a mutable object into a HashSet, change a field the hashCode uses, and check whether contains still finds it.
  4. Insert the same keys into HashMap and TreeMap, print both, and explain the iteration order you see.
  5. Read a list 1,000 times for every write, and compare Collections.synchronizedList with CopyOnWriteArrayList.

Key facts

  • Tarmac has 36 Java interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
  • Tarmac tracked 1,620 job postings asking for Java in November 2026.
  • Roles asking for Java advertise a median base salary of £80,000, across 373 job postings as of November 2026.
  • Tarmac last reviewed these Java interview questions on 16 November 2026.

At a glance

Questions10 shown · 36 in the bank
Difficulty1–5 of 5
FormatsMultiple choice, Short answer, Flashcard, Find the bug, Code output, Multiple answer, True / false, Fill in the blank, Ordering

What you'll review

  1. collections framework
  2. comparable comparator
  3. hashmap internals
  4. list set map
  5. equals hashcode

Practice questions

Try one before you open the answer. Pick an option and press Check; it's marked on the spot.

Which interface is the top-level root of the Java Collections Framework inheritance hierarchy (the immediate super-interface of List, Set, and Queue)?#

Options

Show answer

The root interface of the Java Collections Framework is java.util.Collection. List, Set, and Queue all extend it directly. Iterable sits above Collection but is a general-purpose iteration contract, not the Collections Framework root, and Collections is a utility class, not an interface.

Why:

In the Java Collections Framework, java.util.Collection is the root interface that List, Set, and Queue directly extend. Iterable is the super-interface of Collection, but it is not considered the root of the Collections Framework itself — it is a more general interface for anything that can be iterated. Collections (with an 's') is a utility class, not an interface.

In Java, which interface must a class implement to define its own natural ordering (so that a list of its instances can be sorted without passing a separate comparator)?#

Show answer

java.lang.Comparable

Why:

Implementing java.lang.Comparable<T> and overriding its single method compareTo(T o) establishes the natural ordering for a class. Collections.sort (or List.sort) can then sort a list of those objects without needing an external Comparator.

In Java, what does the Comparable<T> interface require a class to implement, and what do the sign conventions of compareTo(T o) mean?#

Show answer

A class implementing Comparable<T> overrides int compareTo(T o). A negative return value means this should sort before o, zero means they are considered equal for ordering, and a positive value means this sorts after o. The ordering defined by this method is called the class's natural ordering, used automatically by Collections.sort, TreeSet, TreeMap, and similar sorted structures.

Why:

Comparable defines the natural ordering inside the class itself. The compareTo return sign maps to before/equal/after and is the single method of the java.lang.Comparable interface.

The Employee class below is used as a key in a HashMap. Per the design spec, an employee's identity is defined by id and name only; email is a mutable contact field that is NOT part of identity, so two Employee objects that share id and name must be treated as the same key even if their emails differ. The class violates the equals/hashCode contract under that spec. Identify the single buggy line (1-based).#

import java.util.Objects;

public class Employee {
    private int id;
    private String name;
    private String email;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee e = (Employee) o;
        return id == e.id && Objects.equals(name, e.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, email);
    }
}
Show answer

The bug is on line 18.

Why:

Under the stated spec, identity is id and name only, so equals (which compares just id and name) is correct. The bug is in hashCode, which also feeds email into Objects.hash(id, name, email). Two employees with the same id and name but different emails are equal according to equals yet produce different hash codes, which breaks the contract that equal objects must have equal hash codes; a HashMap lookup can then miss a key that equals says is present. The fix is to hash only the identity fields: return Objects.hash(id, name);.

What is the exact output of the following Java program?#

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 2, 3));
        Set<Integer> set = new HashSet<>(list);
        Map<Integer, String> map = new HashMap<>();
        for (Integer n : set) {
            map.put(n, "v");
        }
        map.put(1, "w");
        System.out.println(list.size() + " " + set.size() + " " + map.size());
    }
}
Show answer
4 3 3
Why:

The ArrayList is constructed from four elements (1, 2, 2, 3), so list.size() is 4. The HashSet is constructed from that same list; since a Set rejects duplicates, the two 2's collapse into one entry, giving set.size() = 3. The loop adds one map entry per unique set element (keys 1, 2, 3), so the map has 3 entries. The final map.put(1, "w") updates the value for the existing key 1 but does not add a new key, so map.size() stays 3. The printed output is therefore 4 3 3.

You override equals() on a class but forget to override hashCode(). You then use instances as HashMap keys. What goes wrong?#

Options

Show answer

Lookups break: two objects that are equals can produce different hash codes, land in different buckets, and a get() with an equal-but-distinct key returns null. HashMap uses hashCode() to choose a bucket and equals() only within it, and the contract requires equal objects to have equal hash codes. The default identity-based hashCode() violates this, so always override both together using the same fields.

Why:

The equals/hashCode contract requires that equal objects return equal hash codes. HashMap first uses hashCode() to pick a bucket, then equals() to find the entry within it. The default Object.hashCode() is identity-based, so two distinct-but-equals objects almost always produce different hash codes, route to different buckets, and a get() with an equal-but-not-same key returns null — the entry is effectively lost. It is not a compile error: the compiler never forces you to override both, which is exactly why this bug is so common. Always override hashCode() whenever you override equals() (and prefer the same fields in both).

Which of the following statements about the Java Collections Framework (Java 17 LTS) are true?#

Options

Pick every one that applies.

Show answer

The true statements are: LinkedHashMap maintains insertion order by default and can switch to access-order; EnumSet uses a bit-vector implementation and is not thread-safe; and TreeSet requires elements to implement Comparable or a Comparator at construction. The false ones: CopyOnWriteArrayList uses a snapshot iterator that never throws ConcurrentModificationException, and PriorityQueue does not return elements in sorted order when iterated — only peek/poll respect heap ordering.

Why:

a is true: LinkedHashMap uses a doubly-linked list running through its entries, preserving insertion order by default. The constructor LinkedHashMap(int, float, boolean) with accessOrder=true switches it to access-order (LRU) mode.

b is false: CopyOnWriteArrayList creates a snapshot of the underlying array at iterator-creation time. Its iterator never throws ConcurrentModificationException — it simply reflects the list's state when the iterator was created, even if other threads modify the list concurrently.

c is true: EnumSet is an abstract class whose concrete subclasses (RegularEnumSet for ≤64 elements, JumboEnumSet otherwise) store elements as bit fields in a long[]. Like most non-concurrent collections in java.util, it is not thread-safe.

d is true: TreeSet is a NavigableSet backed by a TreeMap. It relies on natural ordering (elements must implement Comparable) or an explicit Comparator provided via a constructor. If neither is available and elements are not mutually comparable, operations will throw ClassCastException at runtime.

e is false: PriorityQueue is a binary heap. It guarantees that peek()/poll() return the least element (per the ordering), but its Iterator traverses the underlying array in arbitrary heap order — not sorted order.

Correct answers: a, c, d.

In Java 8 and later, ConcurrentHashMap rejects both null keys and null values with a NullPointerException, whereas HashMap accepts both null keys and null values.#

Options

Show answer

ConcurrentHashMap does not allow null keys or null values — both throw NullPointerException — while HashMap permits a single null key and any number of null values. The restriction is deliberate: in a concurrent map a null return from get would be ambiguous between 'absent key' and 'mapped to null,' and the containsKey workaround is not safe against races.

Why:

HashMap explicitly permits one null key and any number of null values. ConcurrentHashMap, by contrast, throws NullPointerException on any attempt to insert a null key or null value. This restriction is intentional: in a concurrent map, ambiguities arise if get returns null because it cannot distinguish 'the key maps to null' from 'the key is absent.' Eliminating nulls removes that ambiguity and avoids the need for the containsKey workaround that single-threaded HashMap callers can use.

In java.util.HashMap (JDK 8+), when the number of entries in a single bucket's linked list reaches the treeification threshold of _____ (the default value of the TREEIFY_THRESHOLD constant), HashMap does not immediately convert that bucket to a red-black tree. It first checks whether the table capacity is at least _____ (the value of the MIN_TREEIFY_CAPACITY constant). If the table is smaller than that minimum, HashMap performs a resize (doubling the table) instead of treeifying, because resizing spreads entries across more buckets and is generally more effective when the table is still small.#

Show answer

In java.util.HashMap (JDK 8+), when the number of entries in a single bucket's linked list reaches the treeification threshold of 8 (the default value of the TREEIFY_THRESHOLD constant), HashMap does not immediately convert that bucket to a red-black tree. It first checks whether the table capacity is at least 64 (the value of the MIN_TREEIFY_CAPACITY constant). If the table is smaller than that minimum, HashMap performs a resize (doubling the table) instead of treeifying, because resizing spreads entries across more buckets and is generally more effective when the table is still small.

Why:

The TREEIFY_THRESHOLD constant is defined as 8 in HashMap's source. When a bin reaches 8 entries, the treeifyBin method is called, but it first checks if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY), where MIN_TREEIFY_CAPACITY = 64. If the table length is below 64, the method calls resize() instead of converting the bin to a tree. Only when the table has at least 64 slots will the linked list in that bucket be replaced with a TreeNode-based red-black tree. This design choice reflects the fact that resizing is cheaper and more broadly beneficial when the table is still small, whereas treeifying individual buckets becomes worthwhile only at larger table sizes where collisions are due to genuinely bad hash distribution rather than an undersized table.

Given the following Java code, arrange the five Employee records in the order they would appear after emps.sort(cmp) completes.#

Put these in order

Show answer

After sorting, the order is Eve, Carol, Bob, Alice, Dave. The comparator sorts by salary descending, then name descending (because a pre-reversed comparator is passed to thenComparing), then years ascending. reversed() negates only the comparator it is called on, so the salary and name stages are both descending while the years stage is ascending.

Why:

The comparator chain applies three stages: (1) salary descending via comparingInt(salary).reversed(), (2) name descending via thenComparing(comparing(name).reversed()), and (3) years ascending via thenComparingInt(yearsOfService). Salary descending puts the two 120 000 employees (Carol, Eve) first, then the two 90 000 employees (Alice, Bob), then Dave at 80 000. Within the 120 000 tie, name descending orders "Eve" before "Carol" (E > C), giving Eve then Carol — years never come into play because names differ. Within the 90 000 tie, name descending orders "Bob" before "Alice" (B > A), giving Bob then Alice. Dave is alone at 80 000. Final sorted order: Eve (e), Carol (c), Bob (b), Alice (a), Dave (d). The critical subtlety is that reversed() is scoped: it negates only the comparator instance it is invoked on, not subsequent thenComparing appendages, and the second-stage name comparator was independently reversed before being passed in.

Related interview questions

Job market

See java salaries and hiring demand from live job postings.

The other 26 questions

This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 26 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.

Start with this topic

Free · the whole bank · 100 answers per 30 days, each marked with written feedback

Interview booked? Practise the job ad instead

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.