简体   繁体   中英

C# Equals and GetHashCode

There's a job interview question I encountered some days ago: How can 2 C# objects or primitive types have the same result for their un-overridden GetHashCode() method but Equals() false? I was directed to the primitive type long and couldn't think of a solution for that.

The rule is that if Equals returns true, then GetHashCode must return the same value, but not the other way around.

Consider this: GetHashCode returns an int. The Type long has more possible values than the Type int. This means that more than one long value will produce the same hash code as another long value. This is called the Pigeon-Hole Principle: http://en.wikipedia.org/wiki/Pigeonhole_principle

A hashcode is a 32-bit integer - how are you going to get a unique hash for every 64-bit long?

A hash-code is supposed to be as-unique-as-possible in order to be as efficient as possible. Equality is a mathematical rule which can't be broken.

This is mathematics. The pigeonhole principle states that if you have 101 pigeons to put in 100 holes, than you will have to put 2 pigeons in the same hole.

As follows, if you have 2^64 possible longs, and 2^32 possible hashcodes (signed int), then you're bound to get the same hash code for different longs.

Well, since long is 8-byted and int is only 4, you can say there will be A LOT of hash code collisions.

For example, 5 and 4294967300 have the same hash code. Which is 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM