~ Mansukh
Censorship is the younger of two shameful sisters, the older one bears the name inquisition.
-- Johann Nepomuk Nestroy
Peter Taucher wrote:HashMap#put checks following:
1) hash == hash
2) key == key || key.equals(key)
Both conditions must be met to determine if the key is already in the map.
First you put 't1' into the map. There're no other keys in the map, so it succeeds.
Then you put 't2' into the map. Because t1.equals(t2) delivers true and both keys have the same hashcode, the map says 'this key is already in the map' and overwrites it / replaces it's value to 'payBills'.
Then you put 't3' into the map. Because the equals method delivers false (the same hashcode isn't enough), the map says 'this key is not yet in the map' and inserts it.
Please correct me if I'm wrong.
~ Mansukh
Mansukhdeep Thind wrote:
Peter Taucher wrote:HashMap#put checks following:
1) hash == hash
2) key == key || key.equals(key)
Both conditions must be met to determine if the key is already in the map.
First you put 't1' into the map. There're no other keys in the map, so it succeeds.
Then you put 't2' into the map. Because t1.equals(t2) delivers true and both keys have the same hashcode, the map says 'this key is already in the map' and overwrites it / replaces it's value to 'payBills'.
Then you put 't3' into the map. Because the equals method delivers false (the same hashcode isn't enough), the map says 'this key is not yet in the map' and inserts it.
Please correct me if I'm wrong.
Thanks Peter :)
~ Mansukh
YesMansukhdeep Thind wrote: Does HashSet also check these two ??
Campbell Ritchie wrote:Another problem about keys in HashMap, or elements in HashSet: if you enter mutable objects, any change in their returned hash code may prevent you from finding the object again.
~ Mansukh
You're welcomeMansukhdeep Thind wrote: . . . Thanks sir.
Page 33 in Bloch, second edition.Will go through the book by Joshua and revert if I have any doubts about equals().
Campbell Ritchie wrote:
You're welcomeMansukhdeep Thind wrote: . . . Thanks sir.
Page 33 in Bloch, second edition.Will go through the book by Joshua and revert if I have any doubts about equals().
This post by Garrett Rowe contains another useful link.
~ Mansukh
There is another way to do it, if you have a copy by your elbow. You open the book, find "Equals" in the index or otherwise, and the page has a 3 and a 3 onMansukhdeep Thind wrote: . . . page numbers as well. . . .
Campbell Ritchie wrote:
There is another way to do it, if you have a copy by your elbow. You open the book, find "Equals" in the index or otherwise, and the page has a 3 and a 3 onMansukhdeep Thind wrote: . . . page numbers as well. . . .
~ Mansukh