Well the short answer is "Not really". Even if you do so, there is not harm, but no magic is gonna happen.
The garbage collector thread, when it runs, it's intelligent enough to understand which Objects doesn't have any references anymore, and it garbage collects it. The present day jvm's are well writen to handle this.
Joined: Oct 08, 2009
Ah, so there is nothing you can do as a programmer to speed it up, it just collects garbage when it decides to?
There is nothing wrong with this program. It would pass every test but there is one problem. The stack maintains obsolete references to objects that were popped off the stack and will not be garbage collected. An obsolete reference is simply a reference that will never be dereferenced again. In extreme case, the program may fail with OutOfMemoryError.
The corrected version of the pop method looks like this:
Michael Keisu wrote:it just collects garbage when it decides to?
That's right. When an object can no longer be reached within your program the GC will remove the object and free the memory it occupied. You don't control this process but the GC guarantees that before it throws an out-of-memory exception it will first make sure all objects you no long use are removed from memory.
There are two special situations you must pay attention to though. The first concerns objects which allocate OS resources. Such objects usually have a special "dispose" method you must call before you let go of them. If you don't the GC won't be able to remove such objects. You'll have to pay attention to the class documentation here.
The second concern is so called "involuntary object retention". This is when you keep a reference to an object but you really didn't mean to. An example (concerning a stack implementation) has been given in this thread.
Apart from this you just create objects when you need them and then stop using them when you're done with them.