I am trying to get my head around the following subject; if you have a hashmap and use Objects for keys, the results when you change attributes of the Objects seems to be strange. For example
As I understand it, when you try to lookup a value in a hashMap, first the hashCode is computer and then the objects are compared for equality. After we change d1.name we can no longer find the "dog key" because although hashCode is the same (6) the equals will fail (clover!=slover).
So why then does the last line also print null? As far as I can see the hashCode AND the equality test should return true.
Is it because I am trying to find it with a "new" Dog Object and not the actual d1 object? If I were to clone d1 and use the clone instead might that work?
I don't see how you say the equality test is true at the end; the new and old objects have different names.
The short answer is, though, that immutable objects make the best keys, and objects with hashcodes or equality criteria that can change while the key is in the map make completely unsuitable keys -- never use such an object as a key in a Map, period.