I have a HashSet
and when I use the Add
method of the collection, nothing is added. The output is still 2, 3, 5, 7, 11, 13
and the output from .Count
is 6.
Is this a bug or am I doing something wrong here?
namespace AllerDiz
{
class MainClass
{
public static void Main (string[] args)
{
HashSet<int> smallPrimeNumbers = new HashSet<int> { 2, 3, 5, 7, 11, 13 };
smallPrimeNumbers.Add (3);
smallPrimeNumbers.Add (5);
smallPrimeNumbers.Add (7);
Console.WriteLine ("{0}", smallPrimeNumbers.Count);
foreach(int val in smallPrimeNumbers)
{
Console.WriteLine ("HashSet Value= {0}", val);
}
}
}
}
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
HashSet doesn't allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten. HashSet allows null values, however if you insert more than one nulls, it would override the previous null value.
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.
In HashSet, we store objects. It does not allow duplicate keys, but duplicate values are allowed. It does not allow duplicate values. It can contain a single null key and multiple null values.
No, this is not a bug. This is precisely how a HashSet
is supposed to work.
The
HashSet<T>
class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
So, if the item you are trying to add already exists in the set, the set is not modified.
If you want a collection which does allow duplicates, look at List<T>
.
From HashSet<T> Class
The HashSet class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
From HashSet<T>.Add Method
Return Value true if the element is added to the HashSet object; false if the element is already present.
HashSet
is a kind of optimized collection. Its constructor eliminates the non-unique elements.
For example;
string[] array = new string[] {"one", "one", "two", "two", "three", "three"};
HashSet<string> hash = new HashSet<string>(array);
string[] array2 = hash.ToArray();
array2
will be {"one", "two", "three"}
If you want to add duplicate values, List<int>
collection allows you to add duplicate values.
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