As inspired by @sealabcore's "Return only duplicate values from ruby array."
Instead of extending from HashSet (Disclaimer)
and falling into the trap of a NullPointerException.
Or using composition forcing you to create delegate calls to the backing Set and making sure all necessary method calls go through your modified #add(E e) method, you can use the notion of aspects.
Note that the constructor
is actually calling the #addAll(Collection<? extends E> c) method which in return calls #add(E e) thus filtering the elements on construction.
What's cool is that the way its integrated, any method used to traverse the returned Set will give you the expected elements. (Note)
Disclaimer Technically speaking we do extend from HashSet only anonymously
Note Although we haven't effectively changed the contract of the Set ("A collection that contains no duplicate elements"), its implementation certainly differs, so make sure you document that