Friday, April 25, 2008

At last HashSet in .NET 3.5

Hi
A few days ago I found a new collection HashSet (System.Collections.Generic namespace).
I am personally waited for this since I first saw it in JAVA 1.4.2.
HashSet is a combination betwin a Set and A Dictionary. Each element can be found only once. Add, Remove, Contains In O(1) - expected (if no rehash is required) just like Dictionary.
It has some new cool methods like UnionWith, IntersectWith.
Small (and simple) Exmaple:

HashSet<int> theSet1 = new &nbspHashSet<int>();
theSet1.Add(1);
// Return true
theSet1.Add(2); // Return true
theSet1.Add(2); // Return false
// theSet1 contains 1,2

HashSet<int> theSet2 = new HashSet<int>();
theSet2.Add(1);
// Return true
theSet2.Add(3);
// Return true
theSet2.Add(4);
// Return true
// theSet2 contains 1,3,4

theSet1.UnionWith(theSet2);
// theSet1 contains 1,2,3,4

theSet1.IntersectWith(theSet2);
// theSet1 contains 2

  • Unlike ICollection.Add : void In HashSet.Add : bool
If you are using HashSet default constactur then you will get a defult comperator (just like in the example above). One thing that you might like to do is to create your own comperator for example we cna create a odd even comperator

class OddEvenComparer : IEqualityComparer {
public OddEvenComparer() {}
public bool Equals(int x, int y) {
return (x & 1) == (y & 1);
}

public int GetHashCode(int x) {
return (x & 1);
}
}


// Now we will use the comperator
HashSet<int>
oddEvenSet= new HashSet<int>(new OddEvenComparer());
oddEvenSet.Add(1);
// Return true
oddEvenSet.Add(3);
// Return false (we allready have an odd number)
oddEvenSet.Add(4);
// Return true
// oddEvenSet will now hold 1,4 (3 is equal to 1 accurding to our OddEvenComparer)

For more information about HashSet you can read in the MSDN http://msdn2.microsoft.com/en-us/library/bb359438.aspx
For Set definition from Wikipedia:
http://en.wikipedia.org/wiki/Set

Enjoy

1 comment:

Anonymous said...

Great post...