Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashMap doubt?

 
Ramana Uppala
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sroring a class object with variable qty value 10 in HashMap.
Later i retrived the object and made changes(set qty 20).
This value is updated in Object stored in Hashmap?
Plaese exaplin this.

import java.util.*;
public class MapTest
{ public static void main(String args[])
{ HashMap hMap=new HashMap();
DobCheck obj=new DobCheck();
obj.setQty(10);
String temp="check";
hMap.put(temp,obj);
DobCheck obj1=(DobCheck)hMap.get("check");
System.out.println("value is "+obj1.getQty()); // value is 10
obj1.setQty(20);//modifying the value of retrived object
DobCheck obj2=(DobCheck)hMap.get("check"); //fetching original
System.out.println("value is "+obj2.getQty());///value is 20?
}
}
import java.io.Serializable;
public class DobCheck implements Serializable
{ private int qty=0;
public void setQty(int qty)
{ this.qty=qty;
}
public int getQty()
{ return this.qty;
}
}
 
Sumit Deshpande
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ramana Uppala:
I am sroring a class object with variable qty value 10 in HashMap.
Later i retrived the object and made changes(set qty 20).
This value is updated in Object stored in Hashmap?
Plaese exaplin this.


Because, both the references are pointing to same object. When you say hashMap.get("key"), it will return you a reference to the stored object. So if you do any operation using that reference (ie. if you call any method on that reference), it will update the object refered by the reference.
e.g. Say i have an object on heap - o1 and i have a reference to the object say r1.
I add that object reference to a hashmap ie. hashMap.put("key",r1).
Now i say hashMap.get("key") . This will return me a reference which points (or rather referes) to o1. So obviously, if i call any method on the referece, it will update the object o1. Since the reference in hashmap is also pointing to same object, you will see the change when you do a hashMap.get("key") and check the value.

Hope this helps...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic