Video in progress
How long does ArrayList.contains() take, and how can you speed it up?
contains scans the list from start to end using equals, so it is O(n). If you ask "is it there?" many times, moving the data into a HashSet brings it close to O(1).
📖 Answer
On one project there was code like this:
List<Long> blockedIds = repo.findBlockedIds(); // 50,000 items
for (Order o : orders) { // 100,000 items
if (blockedIds.contains(o.getUserId())) { ... }
}
That can go up to 5 billion comparisons. Changing one line is enough:
Set<Long> blockedIds = new HashSet<>(repo.findBlockedIds());
Now every check costs, on average, one hash computation and a couple of equals calls.
indexOf and remove(Object) are O(n) in the same way. If the list is sorted, Collections.binarySearch gives you O(log n), but you have to maintain the order yourself.
Sign up to mark studied questions and save your progress.