Guest User

Untitled

a guest
May 26th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. // Can you spot the "memory leak"?
  2. public class Stack {
  3. private Object[] elements;
  4. private int size = 0;
  5.   private static final int DEFAULT_INITIAL_CAPACITY = 16;
  6.   public Stack() {
  7.   elements = new Object[DEFAULT_INITIAL_CAPACITY];
  8.   }
  9.   public void push(Object e) {
  10.   ensureCapacity(); elements[size++] = e;
  11.   }
  12.   public Object pop() { 
  13.   if (size == 0) throw new EmptyStackException(); 
  14.   return elements[ - size];
  15.   }
  16.  /**
  17.  * Ensure space for at least one more element, roughly
  18.  * doubling the capacity each time the array needs to grow. */
  19.  private void ensureCapacity() { if (elements.length == size)
  20.  elements = Arrays.copyOf(elements, 2 * size + 1); }
  21. }
Add Comment
Please, Sign In to add comment