Hi Friends,
Given the code:
The output of above program is: Hi Nitin the product of name.length()*age*salary for both the objects=90
and above formula is used for equals method
hi Nitin inside equals method ....returning TRUE....
Let's see what is returned by equals() method=true
Hi Nitin inside hashCode() method ...returning hashVal=45
Let's see what is the hashCode of object a=45
Hi Nitin inside hashCode() method ...returning hashVal=3
Let's see what is the hashCode of object b=3
So clearly hashCode is not same for above objects !!
Hi Nitin inside hashCode() method ...returning hashVal=45
Hi Nitin inside hashCode() method ...returning hashVal=3
Let's retrieve the objects now
Hi Nitin inside hashCode() method ...returning hashVal=45
hm.get(a)First Object
Hi Nitin inside hashCode() method ...returning hashVal=3
hm.get(b)Second Object
Hi Nitin inside hashCode() method ...returning hashVal=45
Hi Nitin inside hashCode() method ...returning hashVal=3
Hi Nitin inside hashCode() method ...returning hashVal=45
The Object retrieved from HashSet=com.dow.bean.NitEqualTest@2d
Hi Nitin inside hashCode() method ...returning hashVal=3
The Object retrieved from HashSet=com.dow.bean.NitEqualTest@3
Notice that equals() method returned true for both the objects but hashCode() method returned different values(45 and 3). This violates hashCode() contract. However there was no problem storing and retrieving both objects in HashMap and HashSet because they first invoked hashCode() method and based on that they stored each object in different bucket(separate memory area).
So what do you think that in above example the equals() method(uncommented one) implementation is correct or the equals() method(commented one) is correct? (Note that I ran the above program as it is) The above was a question in KS Mock
Test that came with CD and while giving answer it was said that both implementations of equals() are correct with regards to hashCode() and equals() contract. Please correct me if I am wrong in saying this...
Thanks & Regards,
Nitin
[ August 17, 2007: Message edited by: Burkhard Hassel ]
[ August 17, 2007: Message edited by: Burkhard Hassel ]