ConceptDifficulty: Intermediate1 min

Sets: How a HashSet Decides What Counts as a Duplicate

One hash lookup replaces a loop inside a loop, using hashCode and equals on the elements.

A set holds each distinct element once, and a HashSet decides whether an element is already present by calling its hashCode() and then equals(). The hash picks one small group of candidates, so the check costs about the same however many elements the set holds.

An import reads forty thousand rows, and the same customer appears in nine of them. Checking each new row against everything loaded so far is a loop inside a loop, and it is why the import takes eleven minutes. A set does the check in one step per row:

java
Set<String> seen = new HashSet<>();

boolean isNew = seen.add(customerRef);

add returns true if the element was not there before and false if it was, so one call both records the element and answers the question. No separate contains and no second pass are needed.

So a set's job is answering "have I seen this?" quickly, and the answer comes from methods on the elements themselves. Refusing a duplicate is what it does with that answer. For the import, that turns forty thousand comparisons per row into a single lookup per row, and minutes into seconds.

← → move through sections and cards