• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt related to HashMap

 
Jolly Tiwari
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic