ExampleDifficulty: Intermediate1 min

HashSet Example: Adding the Same Order Twice

The third add returns false and changes nothing, which is the useful half of the call.

Set.add reports whether the element was new. Adding the same order reference twice to a HashSet, and printing each result and then the final size, shows it directly:

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

System.out.println(refs.add("AB-1"));
System.out.println(refs.add("AB-2"));
System.out.println(refs.add("AB-1"));
System.out.println(refs.size());
text
true
true
false
2

The third add returned false and changed nothing. The set did not throw, did not replace the element and did not complain; it reported that the element was already present.

The two "AB-1" strings are equal by equals and have the same hash code, which String guarantees. With a class that overrides neither method, the same code prints true three times and a size of three, because every object then counts as different. That is the most common reason a set of your own objects "lets duplicates in": the set is working, and the class never said what equal means.