• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

HashMap doubt?

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;
}
}
 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic