I have a static map in my application which populates when I click on a link.
After that it makes lots of objects and store them. Now I have a link which will clear this Map.
Here is my code.
Hello1 hello1 = new Hello1();
hello1.setHello("Helllollo1");
Hello hello = new Hello();
hello.setHello1(hello1);
hello.setHello("Hellollo");
setMap("1", (Object)hello);
Hello1 hello2 = new Hello1();
hello2.setHello("Helllollo1");
Hello helo = new Hello();
helo.setHello1(hello2);
helo.setHello("Hellollo");
setMap("2", (Object)helo);
Hello1 hello3 = new Hello1();
hello2.setHello("Helllollo1");
Hello helo1 = new Hello();
helo1.setHello1(hello3);
helo1.setHello("Hellollo");
setMap("3", (Object)helo1);
Now I have a method removeMap which works as below
public static void removeMap(String key){
if(map.containsKey(key)){
map.remove(key);
}
}
So when I call this method for a single key after adding above three object, is that object Garbage Collected or not?
Yes, after the map is cleared, the objects which were referenced from it will become eligible for garbage collection if there are no other strong references to them.
Note that removing the entry from the map won’t immediately cause garbage collection – it just means the map will no longer be preventing the object from being garbage collected.