Wednesday 15 July 2015

Why is the default hashcode() in java bad?

Default implementation of hashcode provides the unique hashcode value for all object even has same information (different reference).

Hashcode implementation is required to ensure that the Object with same information (different reference) has equal hashcode.

The default implementation works fine if every object is unique. But if you override equals () then you are implicitly saying that objects with different addresses can be equivalent to each other. In that case you have to also override hashCode().

In String class, the two strings are equal and so their hash codes must be equal. But they are distinct objects with different addresses.


String s1 = new String("foo");
String s2 = new String("foo");
s1 == s2         // false, different addresses
s1.equals(s2)    // true, same contents


Using their addresses as hash codes would be an error (default unique for different addresses). Therefore, String overrides hashCode() to ensure that equal strings have equal hash codes. This helps meet hashCode()'s contract, which is:

If a.equals(b) is true, then a.hashCode() == b.hashCode().

Bottom line: If you override equals(), also override hashCode().

1 comment:

  1. hashCode()

    As you know this method provides the has code of an object. Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode.

    public native int hashCode();

    It indicates that hashCode is the native implementation which provides the memory address to a certain extent. However it is possible to override the hashCode method in your implementation class.

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...