1.why equals is been called and name=clovr compared wih clover on line 36 ?
>> Because all objects of Dog has the same hashCode(). Whenever an object is put into a hash map, we need to make sure that the object doesnt already exist. If it already exists, we need to replace the value with the new one. So, once the hashCode() matches, equals() will be called.
2.why equals is been called and name=clover compared wih clovr.i think it should return true as clover exsits in the bucket(created at line 34 an put in the hashmap on line 34) on the line 39 ?
>> The clovr exists first in the bucket. So the comparison is printed. Even though clover exists in the bucket, the equals() is never called due to an optimization in the HashMap.put() which doesnt call equals() if the references are same. Looking at HashMap.java source code will give further details. The equals() call was not required to confirm the equality.
3. why the object created new Dog("clover") is being compared to clovr on line 54.i think,complier should compare d1 with the being passed in the get function on line 54 and should return true.
>> true has been returned as part of line 54's get() call. Before that the clovr is compared due to the equality in hashCode().
4.why equals is been called and name=clover compared to clovr.As d1 exists in the bucket,it should straightaway ,display the value at key d1.The equals returns false then ,why is it displaying it's content as the output of line 50..The code is at line 50.
>> The compiler is never as intelligent as human. It will need to search all the objects in the bucket in linear order. As said for qn 2, "clovr" is at the start of the bucket. A key with a different value like "mohit" may probably sit later in the bucket and hence may avoid "equals false" comparisons. Sorry though if "mohit" also sits earlier.
5.why equals is been called clovr been compared with name=arhtur ?.The equals method returns false,then why is it output of line 61 giving contents at d1,it should give null as output ?
>> Please refer to answers for questions 2 and 4.
Regards,
Vinayagar