.net - Hash code in Dictionary -
.net - Hash code in Dictionary<TKey, TValue> -
i playing around dictionary , stumbled across below scenario
public class myobject { public string { get; set; } public string j { get; set; } public string k { get; set; } public override int gethashcode() { int hashcode = (i+j+k).gethashcode(); debugger.log(9, "info", hashcode.tostring() + system.environment.newline); homecoming hashcode; } } class programme { static void main(string[] args) { myobject obj1 = new myobject() { = "hello", j = "world" }; myobject obj2 = new myobject() { = "hello", j = "world" }; dictionary<myobject, string> collection = new dictionary<myobject, string>(); collection.add(obj1, "1"); var result = collection[obj2]; // keynotfound exception here. } }
i have myobject class acts key dictionary , override gethashcode method homecoming hash code based on values stored in class.
so, when above code executed, both obj1 , obj2 returns same hash code, still dictionary throws keynotfound exception.
any reason why such behavior?
in .net, gethashcode
used in concert equals
method determine object equality regard storage in collections.
note hash table more complex mapping key single slot via hash code. due nature of hash codes, collisions can occur , do occur in practice (though hash function should not often). hash table implementations have deal case of 2 different objects generating same hash code , achieved linked list @ each "slot" in hash table. hash code used determine slot , equals
method used determine whereabouts object stored in linked list (in "standard" implementations of hash table).
a word of warning, however: there few reasons override built-in behaviour of gethashcode
. found interesting thread discussing gethashcode
, equals
should worth read: http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c. discusses merit/demerits of changing behaviour, properties of , bad hash functions, required properties of these 2 methods , other goodies.
.net dictionary hashcode
Comments
Post a Comment