Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate values in the Set collection?

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?

like image 610
Johanna Avatar asked Jan 21 '10 20:01

Johanna


People also ask

How does the set collection deal with the duplicate elements?

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.

How do you store duplicate values in a set?

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 .

Can there be duplicate values in a set?

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.

Why duplicates are not allowed in set?

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.


1 Answers

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.).

like image 152
Schildmeijer Avatar answered Nov 11 '22 14:11

Schildmeijer