Ordering & iteration: interview questions & scenarios
These are the ordering and iteration questions I use to separate API memory from production judgment. Small loops and one-line comparators can break sorted sets, throw ConcurrentModificationException, or silently return the wrong order.
Here's how to use this page: read the question, say your answer out loud first, then open the model answer. If a follow-up feels shaky, go back to Comparable vs Comparator, Iterator, ListIterator and every way to iterate, Fail-fast vs fail-safe iterators and ConcurrentModificationException explained.
When would you implement Comparable, and when would you pass a Comparator?
Tests natural order, external strategy, sorted collections
Show answerHide answer
Model answer
Implement Comparable<T> when the type has one obvious natural order, such as String, Integer, or a value object ordered by its stable ID. Pass a Comparator<T> when the order belongs to a use case: sort orders by total on one screen, by customer on another, and by creation time in an export.
compareTo and compare return a sign, not a distance. Negative means left comes first, zero means same ordering slot, positive means left comes after. For sorted collections, zero is a big deal: TreeSet treats compare result 0 as "already present", and TreeMap treats it as the same key.
How I’d say it in the interview
"Comparable is the default order built into the class. Comparator is an outside strategy I pass at the call site. I keep Comparable for one obvious order and use Comparator for business views, tie-breakers and null handling."
Signals depth
Mentioning the contract: antisymmetry, transitivity and consistent ties, plus the recommendation that natural ordering usually be consistent with equals.
Red flags
"Comparable sorts ascending and Comparator sorts descending." Both can do either.
Follow-ups interviewers ask next
What if the class has a natural ID order, but one report needs newest first?
Keep
Comparableby ID if that is truly the natural order, and passComparator.comparing(Order::createdAt).reversed()for the report. Do not change the domain default for one screen.
Debug this comparator: why is the sorted list wrong?
Tests subtraction overflow, Integer.compare
Show answerHide answer
Model answer
import java.util.ArrayList;
import java.util.List;
public class BadComparator {
public static void main(String[] args) {
List<Integer> values = new ArrayList<>(List.of(5, Integer.MIN_VALUE, 3));
values.sort((a, b) -> a - b);
System.out.println(values); // [3, 5, -2147483648]
}
}
The comparator subtracts, and subtraction can overflow. Integer.MIN_VALUE - 1 wraps around to a positive number, so the comparator claims the smallest possible integer is larger than 1.
Use Integer.compare(a, b), Long.compare(a, b), or comparator factories such as Comparator.comparingInt.
How I’d say it in the interview
"The comparator is returning the sign of an overflowing subtraction. The contract wants ordering, not arithmetic distance. I would write Integer.compare or comparingInt every time."
Signals depth
Connecting overflow to comparator contract violations in trees, heaps and sorts, not only to this printed list.
Red flags
"It works unless the numbers are negative". The real issue is the full range and overflow.
Follow-ups interviewers ask next
What if we need descending order?
Use
Integer.compare(b, a)orComparator.<Integer>naturalOrder().reversed(). Do not writeb - aeither.
What does "Comparison method violates its general contract" mean?
Tests comparator contract, TimSort, transitivity
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Write a comparator that sorts orders by customer, then highest total, then ID.
Tests comparator chains, reversed placement, primitive helpers
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Which Java sorts are stable, and why does it matter?
Tests stability, Arrays.sort primitives vs objects, List.sort
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
What does this print, and why can removing inside a for-each sometimes not throw?
Tests ConcurrentModificationException, second-to-last element quirk, modCount
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
An orders list is modified by another thread while you iterate it. Should you choose a fail-fast iterator to prevent inconsistent data?
Tests fail-fast best-effort, synchronization, concurrent collections
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
When would you use CopyOnWriteArrayList, and what is the trade-off?
Tests snapshot iterators, write cost, stale reads
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
removeIf or Iterator.remove: which one do you choose?
Tests safe removal, ArrayList bulk removal, intent
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
You need both keys and values while iterating a map. Do you use keySet() plus get()?
Tests entrySet, map views, extra lookup
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
What's the difference between collection.forEach(...) and collection.stream().forEach(...)?
Tests Iterable.forEach, stream terminal operation, ordering
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Why is an index loop over LinkedList a trap?
Tests List iteration, LinkedList get, O(n^2)
Model answer, how to say it, 1 follow-up: unlock with the Java Pass
Premium question set
Keep reading with the Java Pass
The rest of this question set is part of Java One-Stop Interview Prep: in-depth explanations, diagrams, model answers and how to say them in the interview.
From ₹199 · one-time payment · No auto-renewal