Java Collections Interview Questions, Answered by Running Them

Java collections interview questions are asked as definitions and followed up with a program. Every answer here came from running one on JDK 25 and again on JDK 21. Removing the second-to-last element inside a for-each loop throws nothing and skips the last element. List.of throws on contains(null). new HashMap<>(1000) still resizes once. And a ConcurrentHashMap updated with get then put lost between 154,575 and 290,035 of 800,000 increments.

Java collections interview questions look like vocabulary. What is fail-fast, what does List.of return, how does a TreeSet decide duplicates. The definitions are easy to learn, so the follow-up is a snippet and the question of what it prints.

So every answer below is a program's output. Each ran on JDK 25, then again, compiled with --release 21, in the eclipse-temurin:21-jre image, and every output that does not depend on thread timing was identical. Two questions that usually open this list are left out because they already have their own measured articles: ArrayList against LinkedList and how a HashSet is built from a HashMap, which covers hashCode, mutable keys and null keys.

Why does removing inside a for-each loop throw, and when doesn't it?

The stock answer: the iterator is fail-fast, so modifying the list during a for-each throws ConcurrentModificationException. A five-element list, one run per target:

List<String> list = new ArrayList<>(List.of("a", "b", "c", "d", "e"));
for (String s : list) {
  visited++;
  if (s.equals(target)) list.remove(s);
}
remove a in for-each: ConcurrentModificationException after visiting 1, list [b, c, d, e]
remove b in for-each: ConcurrentModificationException after visiting 2, list [a, c, d, e]
remove c in for-each: ConcurrentModificationException after visiting 3, list [a, b, d, e]
remove d in for-each: no exception, visited 4, list [a, b, c, e]
remove e in for-each: ConcurrentModificationException after visiting 5, list [a, b, c, d]

Removing the second-to-last element does not throw. The loop stopped after four elements and never looked at e. Removing the last element, which looks like the safer case, does throw.

The reason is two lines in the JDK's ArrayList iterator. hasNext() is return cursor != size; and only next() checks for modification. Remove d and the size drops to 4 just as the cursor reaches 4, so hasNext() says the loop is over before anything checks. Remove e and the cursor is 5 against a size of 4, so the loop calls next() once more and that throws.

It becomes a real bug when removing by value:

remove every 4 from [1, 2, 3, 4, 4]: no exception, result [1, 2, 3, 4]
Iterator.remove  -> [1, 2, 3]
removeIf         -> [1, 2, 3]

No exception, and a 4 is still in the list. The ArrayList javadoc warns about exactly this: "Fail-fast iterators throw ConcurrentModificationException on a best-effort basis." It is a debugging aid, not a guarantee, and this program had no second thread. Use Iterator.remove() or removeIf.

List.of, Arrays.asList or unmodifiableList: what is the difference?

"They are all read-only" is wrong for one of them and incomplete for the rest. One program called the same operations on each:

Created with set(0, x) add(x) Source changed later contains(null) Null element
Arrays.asList(array) works, and writes to the array UnsupportedOperationException list sees it false allowed
Collections.unmodifiableList UnsupportedOperationException UnsupportedOperationException list sees it false allowed
List.copyOf(list) UnsupportedOperationException UnsupportedOperationException list does not NullPointerException NullPointerException
List.of(...) UnsupportedOperationException UnsupportedOperationException no source NullPointerException NullPointerException
stream.toList() UnsupportedOperationException UnsupportedOperationException no source false allowed

Arrays.asList is a fixed-size view of the array, not a copy. set worked and the array became [X, b, c]; writing B into the array afterwards showed up in the list.

Collections.unmodifiableList is a view too. It refused add, and then an element added to the list behind it appeared through it: [a, b, c, d]. Unmodifiable is not immutable. List.copyOf took a copy and stayed [a, b, c].

List.of does not only reject nulls, it rejects asking about them. List.of("a", "b", "c").contains(null) threw NullPointerException. The List javadoc says "They disallow null elements", and marks a NullPointerException from contains as optional; these lists take the option. Swapping Arrays.asList for List.of can break a caller that only asked a question.

Stream.toList() is the odd one. It is unmodifiable but accepts nulls, while collect(Collectors.toList()) returned a plain, writable java.util.ArrayList. The Stream API examples cover the collectors around it.

Two older traps from the same program: Arrays.asList(new int[]{1, 2, 3}).size() is 1, because the whole int[] is the single element, and [10, 20, 30, 1].remove(1) gave [10, 30, 1], removing by index rather than the value 1.

Why did my TreeSet drop an element?

Because a TreeSet never calls equals. It decides "already present" with compareTo or its comparator. BigDecimal shows it without any code of your own:

1.0 equals 1.00: false, compareTo: 0
HashSet 3 [1.0, 2.50, 1.00]
TreeSet 2 [1.0, 2.50]

Same values, two sizes. The Comparable javadoc names this exact class as the exception, describing "BigDecimal, whose natural ordering equates BigDecimal objects with equal numerical values and different representations (such as 4.0 and 4.00)."

The production version is a comparator on one field:

record Employee(String name, int age) {}

Set<Employee> byAge = new TreeSet<>(Comparator.comparingInt(Employee::age));
add Employee[name=Asha, age=30] -> true
add Employee[name=Ravi, age=30] -> false
add Employee[name=Meera, age=25] -> true
TreeSet by age: size 2 [Employee[name=Meera, age=25], Employee[name=Asha, age=30]]
contains(new Employee("Nobody", 30)): true
TreeMap by age: {Employee[name=Asha, age=30]=second}

Ravi is gone, and the set claims to contain someone who was never added. The TreeMap line is stranger: after putting Asha with "first" and then Ravi with "second", it kept Asha's key and Ravi's value. Adding .thenComparing(Employee::name) brought the size back to 3.

While you are writing that comparator, do not write (a, b) -> a - b. Sorting MIN_VALUE, 0, MAX_VALUE, -1, 1 with it gave [-1, 0, 1, 2147483647, -2147483648], because the subtraction overflows. Integer::compare sorted it correctly.

Is a PriorityQueue sorted?

Its head is. Nothing else is:

PriorityQueue printed: [1, 2, 4, 5, 3]
PriorityQueue for-each: 1 2 4 5 3
PriorityQueue stream().toList(): [1, 2, 4, 5, 3]
PriorityQueue poll order: 1 2 3 4 5

The queue is a binary heap stored in an array. The JDK source describes the only ordering it keeps: each node is no larger than its descendants, which [1, 2, 4, 5, 3] satisfies. toString, for-each and streams all walk that array in storage order. Only poll() repeatedly takes the smallest. The PriorityQueue javadoc says its iterator is "not guaranteed to traverse the elements of the priority queue in any particular order."

Does new HashMap<>(1000) avoid resizing?

No. The constructor argument is the bucket table's capacity, and the map resizes when it holds more than three quarters of that. A program read the private table array through reflection (it needs --add-opens java.base/java.util=ALL-UNNAMED) after every put:

new HashMap<>()                    1000 entries: resizes 7, table 0 -> 16 -> 32 -> 64 -> 128 -> 256 -> 512 -> 1024 -> 2048
new HashMap<>(1000)                1000 entries: resizes 1, table 0 -> 1024 -> 2048
HashMap.newHashMap(1000)           1000 entries: resizes 0, table 0 -> 2048
new HashMap<>(1334)                1000 entries: resizes 0, table 0 -> 2048

new HashMap<>(1000) rounds up to a 1,024-bucket table, whose threshold is 768, so entry 769 doubles it. The boundary is exact: 768 entries into new HashMap<>(768) resized zero times, 769 into new HashMap<>(769) resized once. At 100,000 entries the default map resized 14 times and the "presized" one still once. JDK 8 printed the same counts for every constructor row.

Java 19 added a method that does the division. Both capacity constructors in the HashMap javadoc now say: "To create a HashMap with an initial capacity that accommodates an expected number of mappings, use newHashMap."

Does ConcurrentHashMap make the code thread-safe?

It makes each call thread-safe. A counter needs two calls. Eight threads, 100,000 increments each across ten keys:

Counter checkThenAct = (m, k) -> {
  Integer v = m.get(k);
  m.put(k, v == null ? 1 : v + 1);
};
Counter merge = (m, k) -> m.merge(k, 1, Integer::sum);
round 1  expected 800,000
  synchronizedMap   get + put    659,745  lost 140,255
  ConcurrentHashMap get + put    527,890  lost 272,110
  synchronizedMap   merge        800,000  lost 0
  ConcurrentHashMap merge        800,000  lost 0

Over nine rounds on JDK 25 and three on JDK 21, get plus put lost 104,646 to 219,907 updates on synchronizedMap and 154,575 to 290,035 on ConcurrentHashMap. Neither map was consistently worse. Two threads read the same value and both write back the same result. merge lost nothing in any of the 24 runs, on either map, because the whole read-modify-write happens inside one call.

The answer is about the method, not the class: merge, compute and computeIfAbsent are atomic per key, and get followed by put is atomic on no map.

The follow-up is nulls. ConcurrentHashMap "does not allow null to be used as a key or value", and the run agreed: put(null, v), put(k, null), get(null) and containsKey(null) all threw NullPointerException. So did Hashtable. A TreeMap with natural ordering threw on a null key but accepted a null value. With nulls banned, a null from get can only mean the key is absent; on a HashMap you need containsKey to tell.

How do you build an LRU cache from a LinkedHashMap?

With the access-order constructor flag and removeEldestEntry:

static class Lru<K, V> extends LinkedHashMap<K, V> {
  final int max;
  Lru(int max) { super(16, 0.75f, true); this.max = max; }
  @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > max; }
}
LRU after a,b,c: [a, b, c]
after get(a):     [b, c, a]
after put(d):     [c, a, d]
after getOrDefault(c): [a, d, c]
after containsKey(a): [a, d, c]
after put(a, 10): [d, c, a]

get moved a to the end, so put(d) evicted b. getOrDefault counted as a use and so did put on an existing key, but containsKey did not. A cache that answers hits with containsKey alone never refreshes them, and evicts entries in active use.

Then the trap. Summing the values with for (String k : map.keySet()) sum += map.get(k); threw ConcurrentModificationException on the access-ordered map, and summed to 6 on an insertion-ordered one. The LinkedHashMap javadoc explains why: "In access-ordered linked hash maps, merely querying the map with get is a structural modification." Iterating entrySet() and reading getValue() on the same map summed to 6 without throwing, and left the order untouched.

Answering collections questions out loud

Every question above has a definition and a consequence, and the consequence gets marked. The iterator is fail-fast, so it can also fail to throw. unmodifiableList blocks writes, so changes to its source still show through. A TreeSet uses compareTo, so the comparator decides what counts as a duplicate. ConcurrentHashMap is thread-safe per call, so a counter still needs merge.

Each program fits on one screen and runs with java File.java on a current JDK; the JDK, JRE and JVM article covers which one is actually running. Watching [1, 2, 3, 4] come out of a loop that removed every 4 sticks better than any definition.

[!TAKEAWAY] The expensive answers are the quiet ones. A loop left a 4 in the list, a TreeSet said it contained a person nobody added, a presized HashMap resized anyway, and a thread-safe map lost up to 290,035 of 800,000 updates. None of those threw. Answer with what the program printed, and the follow-up question is already answered.

Frequently asked questions

Is it ever safe to remove from a list inside a for-each loop?
No. It sometimes fails to throw, which is worse than throwing: removing the second-to-last element ends the loop early without an exception, so the last element is never visited. Use Iterator.remove or removeIf, both of which produced the correct result in the same program where the loop silently left a value behind.
What is the difference between unmodifiable and immutable?
An unmodifiable collection refuses writes made through it. An immutable one also cannot change underneath you. Collections.unmodifiableList is the first kind: it threw UnsupportedOperationException on add, then showed an element added to its source list afterwards. List.copyOf takes a copy, so it did not.
Should a TreeSet comparator be consistent with equals?
Yes, unless dropping elements is what you want. A TreeSet decides duplicates with compareTo or the comparator, never with equals. Two employees of the same age compared by age alone left one in the set, and contains() returned true for a third person who was never added.
Is Collections.synchronizedMap or ConcurrentHashMap better?
ConcurrentHashMap for most shared maps, because it does not put every call behind one lock. Neither makes a sequence of calls atomic. Both lost updates when the code read with get and wrote with put; both were exact when the same update used merge. Choose the map for how it scales, and the method for correctness.
How do I stop a HashMap from resizing?
Size it for the number of entries, not the capacity. On Java 19 and later, HashMap.newHashMap(n) does the arithmetic and resized zero times for 1,000 entries. Before that, pass n divided by 0.75, rounded up: new HashMap<>(1334) resized zero times for 1,000 entries on JDK 8, 21 and 25, while new HashMap<>(1000) resized once on all three.

References

  1. ArrayList (Java SE 21 API)Oracle
  2. ArrayList.java (JDK 21 update repository)OpenJDK
  3. List (Java SE 21 API)Oracle
  4. Comparable (Java SE 21 API)Oracle
  5. PriorityQueue (Java SE 21 API)Oracle
  6. HashMap (Java SE 21 API)Oracle
  7. ConcurrentHashMap (Java SE 21 API)Oracle
  8. LinkedHashMap (Java SE 21 API)Oracle