Sunday, October 31, 2010

equals and hashcode

Object equals will just compare references and hashcode is native which always return difference integer even if objects are same but different instances. So of you override equals and not hashcode for any object being used as a key in hashmap, then I will not get value corresponding to key because it wont be able to find hashcode for new instance of key. As it will look into the wrong bucket (new bucket) if I override hashcode and not equals, even there I wont be able to get the value because I can find the bucket but objects equal check references which will be different for stored object and my key object (new instance of old key object).

1 comment:

  1. if you override hashcode and not equals, then you will get a value but that may not be the correct value.

    If you override equals and not hashcode, then you will get null return value.

    ReplyDelete