HashSet Collection in .net 3.5


.net 3.5 has a new Collection class in System.Collections.Generic namespace called HashSet. As you can understand from the namespace it is in, it’s a Generic collection class – HashSet<T>.

HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operation are O(1). (As opposed to List<T> for example, which is O(n) for Contains and Remove.) HashSet also provides standard set operations such as union, intersection, and symmetric difference.  

HashSet can contain only unique elements. The Add() method of HashSet returns bool indicating whether the element is added to not added to the collection. If the element is already present in the HashSet, it’s not added and the Add method returns false.

Now interesting to note that the signature of Add() method in collections come from ICollection<T> and the Add method signature is
void Add(T item) 

But though HashSet<T> implements ICollection<T>, it’s Add method signature is
public bool Add(T item);

So this means that HashSet’s Add method is it’s own method.

Now the following code sample shows how to use HashSet –

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(1);
numbers.Add(2);
numbers.Add(2);
Console.WriteLine(numbers.Count.ToString()); // output – 4

       HashSet<int> uniqueNumbers = new HashSet<int>();
      
uniqueNumbers.Add(1);
      
uniqueNumbers.Add(1);
       uniqueNumbers.Add(2);
      
uniqueNumbers.Add(2);
       
Console.WriteLine(uniqueNumbers.Count.ToString()); // output – 2

 Here’re some good resources –

MSDN – http://msdn2.microsoft.com/en-us/library/bb359438.aspx
BCL Team Blog post – http://blogs.msdn.com/bclteam/archive/2006/11/09/introducing-hashset-t-kim-hamilton.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s