I have stored an object as a key in WeakHashMap. Now if I change its value and then call the GC and print map, then nothing is there.
public static void main(String[] args) throws InterruptedException{
WeakHashMap map = new WeakHashMap();
Integer obj = new Integer(200);
map.put(obj, "sgdjsgd");
obj=new Integer(20);
System.gc();
Thread.sleep(2000);
System.out.println(map);
}
- expected output:
{200,"sgdjsgd"} - atual output:
{}
With this code you are changing the pointer in the memory that is stored in
obj:Before this line,
objheld a pointer reference tonew Integer(200);Now, instead,
objholds a pointer reference tonew Integer(20);which is different from the previous in the memory.Therefore, because
WeakHashMapholds a weak reference, when the garbage collector runs it collect the object referenced by the map, so when you print the map it shows{}because the pointer saved in the map's key is no more found.