SCJP 1.4, SCWCD1.4, OCA(1Z0-007)
But i am creating new instance of Dog1 as key and trying to access the value from map
Naresh Chaurasia wrote:
I have following question. In the lines
If the values of d1.name is "clover", then i get value "Dog1 key". But i am creating new instance of Dog1 as key and trying to access the value from map. If the value of d1.name is not "clover", the the value returned from map is null. The value of d1.name should not determine the value returned from map, but in this example the value of d1.name determines what values is returned by map.
Please explain.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
SCJP 1.4, SCWCD1.4, OCA(1Z0-007)
Pradeep- Kumar wrote:I think Abimaran Kugathasan explained it. But I will try if that helps you.
You need to understand how HashMap works. Please read relevant K&B book section one more time, it explain in better way.
While putting key-value pair in map, HashMap uses key's hashCode() method to determine which bucket to put in this key-value pair. If your key's hashCode() keep changing depending upon some internal state of object (in this case length of name variable), HashMap is not going to rearrange it self. It will still hold key-value pair in the same old bucket.
While getting objects from Hashmap, it two step process, finding correct bucket (using hashCode() of key) and finding correct object in that bucket(using equals() method of key).
Please try to go through the question once again now. It should clear up your doubt.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Naresh Chaurasia wrote:
If i run the following code
I get the following outpur.
null
Dog1 key
null
null
Still not clear why it is so?
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |