Quick revision
The short answer
HashSet.removeAll inherits AbstractSet's implementation, which picks a strategy by comparing sizes: if the set is larger than the argument it iterates the argument and removes each element, otherwise it iterates the set and calls contains on the argument. Here the set (200,000) is not larger than the list (1,000,000), so it calls ArrayList.contains, a linear scan, 200,000 times, which is up to 200 billion comparisons. Converting idList to a HashSet first, or looping over idList and calling remove, makes it take milliseconds.
What to remember
In this answer, we saw that HashSet.removeAll comes from AbstractSet, which iterates the argument when the set is larger and otherwise iterates the set and calls contains on the argument. With a 200,000-element set and a million-element ArrayList, that means 200,000 linear scans, up to 2 x 10^11 comparisons. Because the branch depends on relative sizes, the same line can switch from milliseconds to minutes when data changes. Converting the argument to a HashSet or looping over the list and calling remove makes the work linear.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
HashSet.removeAll inherits AbstractSet's implementation, which picks a strategy by comparing sizes: if the set is larger than the argument it iterates the argument and removes each element, otherwise it iterates the set and calls contains on the argument. Here the set (200,000) is not larger than the list (1,000,000), so it calls ArrayList.contains, a linear scan, 200,000 times, which is up to 200 billion comparisons. Converting idList to a HashSet first, or looping over idList and calling remove, makes it take milliseconds.
Background to this question
This is a favourite debugging question because the code looks perfectly reasonable. removeAll is a standard method, both collections hold the right data, and with small test data the job runs in milliseconds. Then production data grows and the same line takes minutes. The cause is a size-dependent choice inside the JDK that few people know about until it bites them. In this answer, we will recap what contains costs on a HashSet and an ArrayList, read the removeAll implementation, compute why this call is so slow, see how the same line can switch between fast and slow as sizes change, and fix it.
1A Quick Recap of What contains Costs
Everything here comes down to the cost of one contains call. On a HashSet, contains hashes the element, goes straight to one bucket and compares it with the few entries there, so it takes roughly constant time whether the set holds a hundred or a million elements. On an ArrayList, contains has no index to use. It starts at element 0 and calls equals on each element until it finds a match or reaches the end, so a miss costs a full scan of the list.
For a list of 1,000,000 Long ids, one contains call that does not find its element compares against all million entries, and one that does find it compares against half of them on average. Keep that number in mind: one contains on this list is about a million operations.
2Reading the removeAll Implementation
HashSet does not write its own removeAll; it inherits the one in AbstractSet. In recent JDKs that method looks essentially like this (check the source of your JDK version, as the details have been discussed for years).
- Is set size (200,000) > argument size (1,000,000)?YesWalk idList and call set.remove: fastNoWalk the set and call idList.contains
- For each of 200,000 set elementscall
ArrayList.contains - Each contains scans up to 1,000,000 idslinear search with equals
- Total workup to 200,000 x 1,000,000 = 2 x 10^11 comparisons
4 steps in order. Play them, or step through them one at a time.
The size comparison sends us down the branch that depends on ArrayList.contains.
The idea behind it is sensible: iterate whichever collection is smaller. If the set is bigger, walking the argument and removing from the set means fewer steps. If the argument is bigger, walking the set means fewer steps. But that reasoning assumes contains on the argument is as cheap as remove on the set, and it is only cheap when the argument is itself a hash-based set.
Notice that the method never checks what kind of collection c is. An ArrayList, a LinkedList and a HashSet of the same size all take the same branch.
3Why It Takes Minutes
Now we plug in the numbers. The set has 200,000 elements and the list has 1,000,000, so size() > c.size() is false and the method walks the set. For each of the 200,000 elements it calls idList.contains. Elements that are in the list are found after half a million comparisons on average; elements that are not in the list cost the full million.
That is between 10^11 and 2 x 10^11 calls to Long.equals. Even at a few hundred million simple comparisons per second, that is several minutes of pure CPU, on one thread, for a line of code that should take a fraction of a second. The job is not doing anything wrong logically; it is doing a quadratic amount of work: O(n x m) instead of O(n + m).
A thread dump taken while the job is slow shows the giveaway: the worker thread is always inside ArrayList.indexOf or ArrayList.contains, called from AbstractSet.removeAll.
4The Same Line Can Be Fast or Slow
The most confusing part in production is that the performance depends on the relative sizes. Suppose last month the set had 1,200,000 elements and the list 1,000,000. Then the set was larger, the method walked the list and called HashSet.remove a million times, and the job took well under a second. This month the set shrank to 200,000 because of a data cleanup, and the job suddenly takes minutes. A smaller input made it thousands of times slower.
| Set size | List size | Branch taken | Approximate work |
|---|---|---|---|
| 1,200,000 | 1,000,000 | walk list, set.remove | 1,000,000 hash lookups: milliseconds |
| 200,000 | 1,000,000 | walk set, list.contains | up to 2 x 10^11 comparisons: minutes |
| 200,000 | 1,000,000 (as HashSet) | walk set, hashSet.contains | 200,000 hash lookups: milliseconds |
This is why the bug often appears after an unrelated change, and why a test with small, equal-sized collections never catches it. Any time we call removeAll with a List argument, we are relying on which branch the sizes happen to pick.
5Fixing It
There are two simple fixes, and both make the work linear. The first converts the argument into a HashSet, so that whichever branch runs, contains or remove is a hash lookup. The second avoids removeAll and loops over the list ourselves, calling remove on the set, which is always a hash lookup.
Fix 1 costs extra memory for the temporary HashSet, about 50 bytes per id for a million boxed Longs, so roughly 50 MB, but it keeps the intent readable. Fix 2 needs no extra memory and its cost never depends on the sizes, which is why many teams prefer it as the default. Both take milliseconds instead of minutes.
Another option is removeIf on the set with a predicate that checks a HashSet of ids. Whatever we choose, the rule is the same: never let contains be called on a List inside a loop over a large collection.
6Preventing It From Coming Back
Code review is the first defence: any removeAll, retainAll or containsAll whose argument is a List deserves a second look. Static analysis tools can flag calls to contains on a List inside a loop. A test with production-like sizes, including the case where the set is smaller than the list, catches the regression before it ships.
It also helps to write down the reasoning near the fix in one comment line, such as noting that HashSet.removeAll calls contains on the argument when the set is not larger. Otherwise someone will simplify the loop back into removeAll(idList) during a cleanup.
7Follow-up questions
Does retainAll have the same problem?
retainAll inherited from AbstractCollection always walks the receiver and calls contains on the argument, regardless of sizes. So set.retainAll(list) is always O(n x m) when the argument is a List, not just for some sizes. The fix is the same: convert the argument to a HashSet first.
Why has the JDK not changed removeAll to avoid this?
Changing the strategy would change performance for existing programs in the other direction, and checking the type of the argument does not work in general, because a custom collection may have a fast contains. The behaviour has been discussed for many years in JDK bug reports. Check the implementation in your JDK version rather than assuming, and write code that does not depend on it.
How would you find this in production if you did not know about it?
Take a few thread dumps or a short JFR recording while the job is slow. A CPU profile will show nearly all samples inside ArrayList.indexOf called from AbstractSet.removeAll, which points straight at the line. Then the sizes from the logs explain why it only started recently.
8Conclusion
In this answer, we saw that HashSet.removeAll comes from AbstractSet, which iterates the argument when the set is larger and otherwise iterates the set and calls contains on the argument. With a 200,000-element set and a million-element ArrayList, that means 200,000 linear scans, up to 2 x 10^11 comparisons. Because the branch depends on relative sizes, the same line can switch from milliseconds to minutes when data changes. Converting the argument to a HashSet or looping over the list and calling remove makes the work linear.
Open with
The problem is inside removeAll itself. HashSet inherits removeAll from AbstractSet, and that method compares sizes: if the set is larger than the argument, it walks the argument and calls remove on the set, which is a hash lookup.
Then, if they want more
Otherwise it walks the set and calls contains on the argument. Here the set has 200,000 elements and the list has a million, so the set is not larger and it takes the second branch, calling ArrayList.contains for every one of the 200,000 elements.
ArrayList.contains is a linear scan, so each call compares against up to a million ids, and the total is in the order of 10 to the 11 comparisons, which is minutes of CPU.
The nasty part is that it depends on relative sizes, so the same line was probably fast last month when the set was bigger than the list, and became slow when the set shrank. A thread dump would show the thread sitting in ArrayList.indexOf under AbstractSet.removeAll.
To fix it I either convert the list to a HashSet before calling removeAll, so contains is constant time, or I simply loop over idList and call set.remove for each id, which is always linear and needs no extra memory.
I would also note that retainAll always calls contains on the argument, and since these details have been discussed for years, I would check the implementation in our JDK version and add a test with realistic sizes.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A job calls hugeHashSet.removeAll(idList), where hugeHashSet has 200,000 elements and...": https://scrivio-interview-library.netlify.app/java/sets/d2846fa787/