Video in progress

How does HashSet decide that two elements are "the same"?

It first uses hashCode() to find the bucket the element belongs in, then compares it with the elements in that bucket using equals(). If both match, the new element is not added.

📖 Answer

Inside, HashSet actually uses a HashMap: the element is the key, and the value is one shared dummy object.

record Point(int x, int y) {}

Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
set.add(new Point(1, 2));
System.out.println(set.size()); // 1 — a record generates equals/hashCode itself

If Point were a regular class without equals/hashCode overridden, the result would be 2, because by default every object is equal only to itself.

add() returns a boolean: true if the element is new, false if it was already there. That makes it handy for a "have we seen this before?" check.