It is not enough to override "equals" and then try to retrieve keys in a map... If the 2 objects are equal, then the hash codes have to be the same. I suppose they play a max on this one...
You put an object in a map(the key). Then you change the object. And you base the hash code on the length of the String... The key changed but the method "get" will look in the bucket corresponding to the new hash code and will not find the value...
length("key1") => bucket 4
then you change key1 in "key11"
the object is still in bucket 4 but the hash code will reference the bucket5 !!! because lenght("key11") is... 5 !!!
It is not a good idea to change the key... I pref remove and then add...
To understand the statement on p 554, I propose to study the following example :
String aString = (String) m.get("k1");
The 3 will return "k1"
default : it is the same "k1" from the string pool and hashCode will return the same id
0 : all objects will return the same bucket (bucket 0)
lenght : have the same length (bucket 2)
default : You do a new 2 times and the default hashCode will return 2 diffent hash ! You will not be able to retrieve the values !!!
0 and length will return the hash same thus we can retrieve the keys.
It is the same object and can be found in the 3 cases.
The key is changed !!! It was "cloverkey" and now it is "1" !
This time we change the key ! The hash code will make a difference...
def and 0, both point to the same bucket
length("clovervalue") and length("1") are different... Java will try to find the key in the wrong bucket !
default : it is a different object because we used the keyword new !
0 : OK They all use the bucket 0 and it is not performant !
lenght : NOK because the length("clovervalue") = 11 and length("1") = 1 the value is in bucket 11 and we try to find the value in bucket 1 !
If you use 0 you put all the keys and values in the same bucket !