The following code is available:

public class Fish { private readonly string name; public Fish(string name) { this.name = name; } public override int GetHashCode() { return name.GetHashCode(); } public override bool Equals(object obj) { var otherFish = obj as Fish; if (otherFish == null) { return false; } return otherFish.name == name; } } class Program { static void Main() { var duplicates = new Hashtable(); var key1 = new Fish("Herring"); var key2 = new Fish("Herring"); var key3 = new Fish("Herring2"); duplicates[key1] = "Hello"; duplicates[key2] = "Hello2"; duplicates[key3] = "Hello3"; Console.WriteLine(duplicates.Count); // Delay. Console.ReadKey(); } } 

When calling duplicates[key1] = "Hello" and duplicates[key3] = "Hello3" , only GetHashCode () is called, and when calling duplicates[key2] = "Hello3" , Equals () is called. How does the compiler determine when to call Equals () and when there is no need for it?

  • This is determined not by the compiler, but by the implementation of the hash table. You, in duplicates [key2], use a key named "Herring" which has already been added with the line above - that’s their hash codes matched, so Equals volunteered - tym32167

1 answer 1

If simplified, the hash table works like this:

  • GetHashCode() is called for the key.
  • If there is a match with the hash code that is already in the table, the Equals() method is called. The fact that the hash codes coincided does not mean that Equals() returns true
  • If objects are equal, then the entry in the table is overwritten, if not equal, a new one will be added.

duplicates[key2] = "Hello2"; on this line the hash code coincided, but the hash table should check if the key is equal to the key already existing in the table, therefore Equals() is called

In practice, GetHashCode() % table_length is taken as GetHashCode() % table_length , where table_length size of the internal table.

  • In practice, the original hash table (Hashtable) uses the open addressing method to resolve collisions and will iterate over the buckets until it encounters an empty one. In the case of a vehicle, it is there that Equals will be called - referencesource.microsoft.com/#mscorlib/system/Collections/… - Artem Okonechnikov
  • @ ArtyomOkonechnikovu you link is not led to "meet empty" and to "meet busy, or devastated; with the same key." in the case of a topiCastera, there is a busy bake. - PashaPash