Please go through the following code segment, I am not able to clarify how this p.name="XYZ" is able to change the contents of HASHMAP. what i am thinking is after adding Person p2 to the hashmap as a key which happens to be the same as Person p,this key will be overwritten too ,Thus p should not be in the scenario.
Go through the API documentation for Map, then find HashMap from it, then the Java Tutorial, then read them carefully.
The mistake you are making is using a mutable object as a key to a Map; if you alter the state of the key, you may never find the mapping again. See, altering the name field will alter the hashCode so the Map implementation will look for that object in the wrong place and fail to find it.