@PhilWright made some good points. I would add:
- Popping element from an empty stack should throw
java.util.EmptyStackException - Test for memory leaks. Since the Stack is in charge of managing its own memory, this is a real concern. A common memory leak in stack implementations is when removed elements are not nulled out correctly.
Here's one way to verify that pop cleans up after the removed object, based on @DavidHarkness@DavidHarkness' idea in comments, using a WeakReference:
@Test
public void testPopCleansUpReference() {
Object value = new Object();
WeakReference<Object> reference = new WeakReference<>(value);
Stack<Object> stack = new StackImpl();
stack.push(value);
value = null;
stack.pop();
Runtime.getRuntime().gc();
assertNull(reference.get());
}
The current implementation fails this test,
because this implementation only decreases the size variable,
the popped object remains inside the data array:
@Override public Object pop() { --size; return data[size]; }
For the record, the fix is simple enough:
@Override
public Object pop() {
Object result = data[--size];
data[size] = null;
return result;
}