1 package com.midc.spikes.effectivejava.obsoleteobject; 2 3 //Can you spot the "memory leak"? 4 5 import java.util.*; 6 7 public class Stack { 8 private Object[] elements; 9 private int size = 0; 10 private static final int DEFAULT_INITIAL_CAPACITY = 16; 11 12 public Stack() { 13 elements = new Object[DEFAULT_INITIAL_CAPACITY]; 14 } 15 16 public void push(Object e) { 17 ensureCapacity(); 18 elements[size++] = e; 19 } 20 21 22 public Object pop() { 23 if (size == 0) 24 throw new EmptyStackException(); 25 return elements[--size]; 26 } 27 28 /** 29 * 30 * Ensure space for at least one more element, roughly 31 * doubling the capacity each time the array needs to grow. 32 */ 33 34 private void ensureCapacity() { 35 if (elements.length == size) 36 elements = Arrays.copyOf(elements, 2 * size + 1); 37 } 38 39 public int getSize() { 40 return size; 41 } 42 } 43