How to override Equals and GetHash of HashSet

How to override Equals and GetHash of HashSet

Content Index :

How to override Equals and GetHash of HashSet
Tag : chash , By : ChaseVoid
Date : November 23 2020, 03:01 PM

like below fixes the issue It may seems like you solved what you asked for, but there is something important that should be pointed out. When you implemented the EqualityComparer you coded the GetHashCode(int[] i) as return base.GetHashCode(); which is not correct even when it works. I took the time to provide you with the code below for you to see the results of your implementation and I also gave you a possible solution. Copy this code and run it in a Console Project. Comment your line of code, uncomment the line right below it and run it again. You will see the difference! Summarizing, when you return base.GetHashCode() you are returning the same hash code for every item. This causes collisions inside the hash set for all insertions ending up in a behavior as slow as if you were using a List and you were asking if it contains an element before inserting it. That is why you will see that by using the function I provided you and for the range of numbers I'm generating you will be able to insert up to one million times in less than 1 sec. However, using yours, no matter the range, it spends 1 sec in around ten thousand insertions. This happens because for all n insertions there are collisions and the resulting time complexity is O(n^2) when the expected for a HashSet and an even distributed Hash Function is O(n). Check this out:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace hashExample
    class Program
        static void Main(string[] args)
            List<int[]> points = new List<int[]>();
            Random random = new Random();
            int toInsert = 20000;
            for (int i = 0; i < toInsert; i++)
                int x = random.Next(1000);
                int y = random.Next(1000);
                points.Add(new int[]{ x,y });
            HashSet<int[]> set = new HashSet<int[]>(new SameHash());
            Stopwatch clock = new Stopwatch();
            foreach (var item in points)
            Console.WriteLine("Elements inserted: " + set.Count + "/" + toInsert);
            Console.WriteLine("Time taken: " + clock.ElapsedMilliseconds);

        public class SameHash : EqualityComparer<int[]>
            public override bool Equals(int[] p1, int[] p2)
                return p1[0] == p2[0] && p1[1] == p2[1];
            public override int GetHashCode(int[] i)
                return base.GetHashCode();
                //return i[0] * 10000 + i[1];
                //Notice that this is a very basic implementation of a HashCode function

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Overridding Equals and GetHash

Tag : chash , By : kbrust
Date : March 29 2020, 07:55 AM
To fix this issue You should always override GetHashCode.
A Dictionary will function without GetHashCode, but as soon as you call LINQ methods like Distinct or GroupBy, it will stop working.
public override bool Equals(object obj) { return Equals(obj as Person); }
public override int GetHashCode() {
    return FirstName.GetHashCode() ^ LastName.GetHashCode();

How should I override equals and hashcode method to avoid adding equal objects o HashSet?

Tag : java , By : geo
Date : March 29 2020, 07:55 AM
Hope this helps
I have studied similar examples and override these methods like this, but still get added to the HashSet objects with the equal names BUT different id.

How to override equals(), hashcode() and compareTo() for a HashSet

Tag : java , By : koder
Date : March 29 2020, 07:55 AM
I wish did fix the issue. The basic question here is "How can you determine if two objects are equal to each other?"
This is a simple question for simple objects. However, it becomes increasingly difficult with even slightly more complex objects.
public boolean equals(final Object o)
    if (o instanceof MyObject)
        return (0 == this.compareTo(((MyObject) o)));
    return false;

public int hashCode()
    return getKeyValuePairs(this.myMap).hashCode();

// Return a negative integer, zero, or a positive integer
// if this object is less than, equal to, or greater than the other object
public int compareTo(final MyObject o)
    return this.hashCode() - o.hashCode();

// The Map is flattened into a single String for comparison
private static String getKeyValuePairs(final Map<String, String> m)
    final StringBuilder kvPairs = new StringBuilder();

    final String kvSeparator = "=";
    final String liSeparator = "^";

    if (null != m)
        final List<String> keys = new ArrayList<>(m.keySet());

        for (final String key : keys)
            final String value = m.get(key);
            kvPairs.append(null == value ? "" : value);

    return 0 == kvPairs.length() ? "" : kvPairs.substring(liSeparator.length());

For contains should we override both hashcode and equals for hashset in java

Tag : java , By : Amin Amini
Date : March 29 2020, 07:55 AM

How should I override Equals and GetHashCode for HashSet?

Tag : chash , By : user96271
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • What to use for Messaging with C#
  • Accessing a Dictionary.Keys Key through a numeric index
  • ConfigurationManager.AppSettings Performance Concerns
  • What Are Some Good .NET Profilers?
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Generic event test method, preventing code duplication
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • C# XDocument Element/Elements returns null
  • Autofac keyed service with IEnumerable relationship type
  • Installing EntityFramework via NuGet manager
  • Always Check if there is Internet Connection Xamarin forms
  • WCF OneWay service slows down when aspNetCompatibilityEnabled is set to false
  • Can we use JsonRequestBehavior.AllowGet with [HttpPost] attribute?
  • How to customize the Setup wizard with custom forms in Visual Studio setup project
  • C# ASP.NET - Use method from another class to create labels
  • C# List IList or IEnumerable as argument
  • Parsing File with C# And Replace method
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com