Is it possible to allow duplicate values in the Set collection?
Is there any way to make the elements unique and have some copies of them? Is there any functions for Set collection for having duplicate values in it?
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
As community has pointed out in the comments, a Set is not meant to store duplicate values. But for reasons like "interview question" or "library code that you can't change", you can force it to store duplicates by overriding equals to always return false .
Sets cannot contain duplicates. Duplicates are discarded when initializing a set. If adding an element to a set, and that element is already contained in the set, then the set will not change.
The meaning of "sets do not allow duplicate values" is that when you add a duplicate to a set, the duplicate is ignored, and the set remains unchanged. This does not lead to compile or runtime errors: duplicates are silently ignored. Set is implemented like that to avoid duplication.
Ever considered using a java.util.List instead?
Otherwise I would recommend a Multiset from Google Guava (the successor to Google Collections, which this answer originally recommended -ed.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With