Replace GetHashCode () System.Drawing.Point Method

System.Drawing.Point has a really very bad GetHashCode method if you intend to use it to describe the "pixels" in an image / bitmap: it is just an XOR between the X and Y coordinates.

So, for an image with a size of, say, 2000x2000, it has an absurd amount of collisions, since only the numbers in the diagonal will have a decent hash.

It's very easy to create a decent GetHashCode method using unchecked multiplication, as some people have already mentioned here .

But what can I do to use this improved GetHashCode method in a HashSet ? I know that I could create my own / struct MyPoint and implement it using these improved methods, but then I would break all the other parts of the code in my project that use System.Drawing.Point .

Is it possible to "overwrite" a method from System.Drawing.Point using any extension method or the like? Or, to β€œtell” a HashSet use a different function instead of GetHashCode ?

I am currently using SortedSet<System.Drawing.Point> with a custom IComparer<Point> to store my glasses. When I want to know if the set contains a Point, I call BinarySearch . This is faster than the HashSet<System.Drawing.Point>.Contains in a set with 10,000 collimations, but it is not as fast as a HashSet with a good hash.

+6
source share
1 answer

You can create your own class that implements IEqualityComparer<Point> , then provide this class to the HashSet constructor.

Example:

 public class MyPointEqualityComparer : IEqualityComparer<Point> { public bool Equals(Point p1, Point p2) { return p1 == p2; // defer to Point existing operator== } public int GetHashCode(Point obj) { return /* your favorite hashcode function here */; } } class Program { static void Main(string[] args) { // Create hashset with custom hashcode algorithm HashSet<Point> myHashSet = new HashSet<Point>(new MyPointEqualityComparer()); // Same thing also works for dictionary Dictionary<Point, string> myDictionary = new Dictionary<Point, string>(new MyPointEqualityComparer()); } } 
+10
source

Source: https://habr.com/ru/post/987959/


All Articles