Search code examples
javastackeffective-java

why did Joshua Bloch decrement the "size" value of stack in the pop method in effective java?


here is the code from Item 6, pg 24, chapter 2 of effective java 2nd edition, by Joshua Bloch. In the pop method he defines, he uses elements[--size]. I am wondering why he used --size, instead elements[size--] should return the same correct?

public class Stack {
       private Object[] elements;
       private int size = 0;
       private static final int DEFAULT_INITIAL_CAPACITY = 16;
       public Stack() {
           elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
       public void push(Object e) {
           ensureCapacity();
           elements[size++] = e;
}
       public Object pop() {
           if (size == 0)
               throw new EmptyStackException();
           return elements[--size];
}
       /**
        * Ensure space for at least one more element, roughly
        * doubling the capacity each time the array needs to grow.
        */
       private void ensureCapacity() {
           if (elements.length == size)
               elements = Arrays.copyOf(elements, 2 * size + 1);
} }

Solution

  • Because arrays are 0 based indexed.

    Imagine that you have a stack with 2 elements.

    So the size of the stack is equals to 2 with the following representation in the array :

    elements[0] = elem;
    elements[1] = elem;
    

    So you need to decrease size before pop the elem from the stack, otherwise you will try to pop elements[2], which doesn't exists. So an infix operator is used in this case.

    return elements[--size];
    

    is equivalent to

    size--;
    return elements[size];
    

    If elements[size--]; was written, it would try to pop elements[2] and then decrease size by 1. So an ArrayIndexOutOfBoundsException will be thrown each time you want to pop an element from the stack.