memory - java loitering and garbage collection -


i have bit of code stack's pop method , i'm trying figure out how avoids loitering while still returning element our index pointing to:

public string pop() { // remove item top of stack. string item = a[--n]; a[n] = null; // avoid loitering (see text). if (n > 0 && n == a.length/4) resize(a.length/2); return item; } 

from can understand pointing reference item of our string object indexed element(we start last element using it's current size n-1 hence decrements) of our array a. if returning reference why setting indexed element our reference pointing null before doing so? doesnt make item point nothing , return nothing?

an object can't garbage collected long reachable. if change index --n not nullify a[n], keep reference object, preventing garbage collection if client code not reference object longer.

that 1 of cases need nullify variable in java.

you seem misunderstand references are. a[n] contains value points object in memory. when write string item = a[n], copy value variable item. both variables (item , a[n]) refer same object. when write a[n] = null, remove reference array item still contains value points original object.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -