Whether you set emp
to null
or not, is irrelevant. The application logic remains the same; you are putting an entry to the map, never remove it, thus the only valid answer to aMap.size()
is 1
(one).
Even if your assumption, that you can never access the mapping, was right (it isn’t, you can retrieve the Employee
instance via aMap.keySet().iterator().next()
, to name just one example), e.g. if you create a class encapsulating another object that it never hands out, it didn’t allow to change the outcome of calculations based on the encapsulation, like the size reported by the HashMap
.
A simple view on this issue, is, that you are holding a reference to HashMap
, which in turn holds a reference to the Employee
instance.
But actually, these objects can be garbage collected, as long as the JVM ensures the correctness of the program, e.g. ensures that the last print statement produces the output Size of Map1
, which is technically possible without keeping the entire memory of the HashMap
and its referenced objects. It would only have to keep the value of the int size
field, or just remember the predictable string result.
But while this is allowed by the specification, it isn’t guaranteed. Garbage collection is a best-effort process. Collection of such apparently referenced objects only happens for optimized code and the JVM normally doesn’t optimize the code of an application consisting of a single main
method that terminates within a few milliseconds.
The bottom line is, regardless of whether the JVM reclaims the memory behind the scenes, garbage collection will never cause a HashMap
to spuriously change its size.