stack is empty
Thereisaproblemwiththe Stack class:itleaksmemory.Whenyoupushanobject
ontothestack,itsreferenceisstoredintheinternal elements array.Whenyoupopan
objectoffthestack,theobject'sreferenceisobtainedand top isdecremented,butthe
reference remains in the array (until you invoke push() ).
Imagine a scenario where the Stack object's reference is assigned to a class field,
whichmeansthatthe Stack objecthangsaroundforthelifeoftheapplication.Further-
more,supposethatyouhavepushedthree50-megabyte Image objectsontothestack,
timethegarbagecollectorruns.However,thiswon'thappenbecausethe Stack object
not be available to the application, and maybe the application will run out of memory.
The solution to this problem is for pop() to explicitly assign null to the ele-
ments entry prior to returning the reference. Simply uncomment the ele-
ments[top+1] = null; line in Listing 2-49 to make this happen.
You might think that you should always assign null to reference variables when
their referenced objects are no longer required. However, doing so often does not
improve performance or free up significant amounts of heap space, and can lead to
throwninstancesofthe java.lang.NullPointerException classwhenyou're
erage of Java's exceptions-oriented language features). You typically nullify reference
Note Garbage collection is a complex process and has resulted in various garbage
HotSpotVirtual Machine” whitepaper at http://www.oracle.com/technet-