ExampleDifficulty: Intermediate1 min

Adding the Same Order Twice and Getting One Back

Four adds, two of which are the same reference, and the return value of each.

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 and did not complain — it reported that the element was already present, which is the useful half of the call.

What to notice: the two "AB-1" strings are equal by equals and have the same hash code, which is what String guarantees. Substitute a class that overrides neither and the same code prints true three times and a size of three.