File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt  related to HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt  related to HashMap" Watch "Doubt  related to HashMap" New topic

Doubt related to HashMap

Jolly Tiwari
Ranch Hand

Joined: Mar 26, 2006
Posts: 77
Please go through the following code segment, I am not able to clarify how
this"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.

please clarify me wherever i am wrong

import java.util.HashMap;

class Person
String name;

Person(String name)


public boolean equals(Object o)
if((o instanceof Person) && ((((Person)o).name) )
return true;
return false;


public int hashCode()
return name.length();

public String toString()

return name;


class DelIt{

public static void main(String...x)
HashMap hm=new HashMap();
Person p=new Person("first");

hm.put(p,"first Person");

Person p1=new Person("second");

hm.put(p1,"second Person");

Person p2=new Person("first");

hm.put(p2,"third Person");






Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46405
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.
I agree. Here's the link:
subject: Doubt related to HashMap
It's not a secret anymore!