aspose file tools*
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
Author

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 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.

please clarify me wherever i am wrong

import java.util.HashMap;


class Person
{
String name;

Person(String name)
{
this.name=name;

}

public boolean equals(Object o)
{
if((o instanceof Person) && ((((Person)o).name)==this.name) )
return true;
else
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");

System.out.println("12********(*"+hm+hm.size());



p.name="XYZ";


System.out.println("12********(*"+hm);




System.out.println(hm.get(p1));
System.out.println(hm.get(p2));


}
}

Regards

Jolly
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
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: http://aspose.com/file-tools
 
subject: Doubt related to HashMap