public Object pop() { if (size == 0) thrownewEmptyStackException(); return elements[--size]; }
/** * Ensure space for at least one more element, roughly doubling the capacity each time the array needs to grow. */ privatevoidensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } }
publicclassRule6 { publicstaticvoidmain(String[] args) { Stackstack=newStack(); for (inti=0; i < 10; i++) stack.push("1"); for (inti=0; i < 10; i++) stack.pop(); // break point System.out.println("complete"); // break point } }
// Can you spot the "memory leak"? classStack { privatestaticfinalintDEFAULT_INITIAL_CAPACITY=16; private Object[] elements; privateintsize=0;
publicStack() { elements = newObject[DEFAULT_INITIAL_CAPACITY]; }
public Object pop() { if (size == 0) thrownewEmptyStackException(); return elements[--size]; }
/** * Ensure space for at least one more element, roughly doubling the capacity each time the array needs to grow. */ privatevoidensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } }
public Object pop() { if (size == 0) thrownewEmptyStackException(); Objectresult= elements[--size]; elements[size] = null; return result; }
/** * Ensure space for at least one more element, roughly doubling the capacity each time the array needs to grow. */ privatevoidensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } }