0

I've been reading Effective Java, and one thing that came out to me with the obsolete object reference item was his implementation of pop():

public Object pop(){
  if (size == 0)
    throw new EmptyStackException();

  Object result = elements[--size];
  elements[size] = null;
  return result;
}

Why is it necessary to create a new reference to elements? Why not do

elements[size] = null;
return elements[--size]

This nulls out the obsolete object reference without having to create a new recerence to the array.

Jason
  • 11,263
  • 21
  • 87
  • 181

3 Answers3

3

Note that your change reverses the behavior, suppose size = 5, let's see what happens:

Original (-- comes first):

Object result = elements[4];
elements[4] = null;
return result;

Now your change (-- comes second):

elements[5] = null;
return elements[4]

So your implementation will return an incorrect value. The implementation needs to pull out the head, then set it to null as a separate step, otherwise the value being removed is lost. Looking at this implementation you could theoretically not set the values to null, which would save a couple of lines of code, but potentially introduces a rather serious risk of memory leaks (holding onto large objects above the head of the stack after everywhere else has de-referenced them). Additionally, the separate lines makes this behavior more explicit, which is valuable for people revisiting the code later. Verbosity is sometimes your friend.

dimo414
  • 47,227
  • 18
  • 148
  • 244
1

This is because elements[size] = null doesn't make sense before the pre-decrement of size field and would cause the access to go out of bounds.

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
0

In your suggested implementation, you've switched the order so the size when setting to null is not the same index as it is in the one above. If you were to do elements[--size] = null; first, you would loose the reference you're meant to return. For this reason, you need another handle (reference to the data before you clear the internal recording of that reference. You want to remove the internal reference so that the object can be garbage collected if it is no longer needed. Holding it past the size, while not accessible, would result in the GC not being able to release the object.

Andrew Ring
  • 3,185
  • 1
  • 23
  • 28