This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashMap doubt? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashMap doubt?" Watch "HashMap doubt?" New topic
Author

HashMap doubt?

Ramana Uppala
Greenhorn

Joined: Jan 04, 2005
Posts: 16
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

Joined: Jan 10, 2005
Posts: 38
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...
 
wood burning stoves
 
subject: HashMap doubt?
 
Similar Threads
assigning one primitve variable to another primitive variable..
ArrayList, contains, objects
final - access modifier
passing parameters to a method.
object garbage collection.