When you call the second put statement, its key has to be checked against existing keys to see if they are the same. So the equals method is being called. In the equals method, you print out the values of the instance variables of the Info objects.
Just let me run through this so.Is this what happens?
1: A new Info object is created with s1=aaa,s2=aaa and s3=aaa.
2: A 2nd Info object is created with s1=aaa,s2=bbb and s3=ccc.
3: The 1st object called i1key is added to the Map & equals method isnt called.
4: The 2nd object called i2key is added to the Map & equals method is called and i2 is passed into the equals method.
5: In the equals method i.s1+i.s2+i.s3 prints the values of i1 ??
Q. Why does it print these values when i2 is the object in the method? Also are the previous values (if i.s1+i.s2+i.s3 is the case) the ones the comparison is made against and what if there was 3 keys added would the comparison be made against the last values added i2 and not the first ones added i1??
6: In the equals method s1+s2+s3 prints the values of i2. [ January 23, 2007: Message edited by: David Kennedy ]
"There are only 10 types of people in the world: Those who understand binary, and those who don't"
When the key-value will be added to the HashMap first time i.e. map.size()==0 then there will be no equal comparision as there is not element to compare with. So keep this is a sequence of events. 1) At //1. Since the map is of size 0 so there will be no equals() comparion of the keys. 2) At //1 the key - value added into the map. 3) At //2. Since the map has one element to comapre with the incoming key-value so the comparision of the key will take place and the TWO SOPs will be printed.
Also when I change the code to make s1 different then nothing is printed!
Is this because the equals method isnt called because the hashcode is calculated on s1 so therefore will be different and therefore the equals method isnt called or is automatically false? Does this mean the hashcode method is checked before the equals method is? [ January 23, 2007: Message edited by: David Kennedy ]
"There are only 10 types of people in the world: Those who understand binary, and those who don't"
There is no need to check if two objects are equal if they have different hashcode, because hashcode contract says that there MUST NOT be 2 objects which are equal when compared by equals method and have different hashcode...
But when looking at your code example it seems to me, that this combination of equals and hashcode methods does not fullfil this contract.
consider this for example: "aa" "abbb" "ccc" "aaa" "bbb" "ccc"
equals? yes, same hashcode? no
...please correct me if I am wrong...
Victory is the only truth that matters.
expectation is the root of all heartache - shakespeare. tiny ad:
a bit of art, as a gift, the permaculture playing cards