My Blog

August 27, 2009

Rules for Equals() and GetHashCode() methods in .net and Java

Filed under: Uncategorized — Tags: — michaelneuhold @ 1:35 pm

In Java or .NET, if you override equals(), you also have to override GetHashCode(). The rules:

1) if two objects are equal, their hashcodes must be equal too.

2) if two objects have the same hashcode, they need not be equal (since it could just be an accidental hashcode-collision)

3) If the object in question is ever to be used in hash container, it must not change its hashcode during its lifetime. If it does change its hashcode, e.g. after having been added to a hashed collection, it could never be found again since the hash container would look in the wrong bin! And yes, this conflicts with 1) and 2) above – even microsoft didn’t get this right in every place of the .net framework. You can even get away with a sloppy implementation that doesn’t take these rules into account, if you won’t ever use hash containers.

The safest way to go is to make all fields which contribute to hash code calculation immutable .Or make the entire object immutable (which has many more benefits, automatic thread-safety and better sharing of objects among them)

For further info:

http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c

http://stackoverflow.com/questions/462451/gethashcode-guidelines-in-c

Blog at WordPress.com.