Reputation: 1333
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?
Upvotes: 0
Views: 906
Reputation: 310957
Your question embodies a contradiction in terms. If the object, or rather the reference to the Object, has been removed from the Map, it is no longer 'inside the Map' at all.
Upvotes: 0
Reputation: 7899
Yes , When your Map
is cleared or you remove objects from it , objects will be eligible for garbage collection . since objects don't have any reference they are eligible for GC.
Any object which is unreachable or has no reference is eligible for collection.
Upvotes: 0
Reputation: 1501043
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.
Upvotes: 2