Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 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.  
  7. public Stack() {
  8. elements = new Object[DEFAULT_INITIAL_CAPACITY];
  9. }
  10.  
  11. public void push(Object e) {
  12. ensureCapacity();
  13. elements[size++] = e;
  14. }
  15.  
  16. public Object pop() {
  17. if (size == 0)
  18. throw new EmptyStackException();
  19. return elements[--size];
  20. }
  21.  
  22. /**
  23. * Ensure space for at least one more element, roughly
  24. * doubling the capacity each time the array needs to grow.
  25. */
  26. private void ensureCapacity() {
  27. if (elements.length == size)
  28. elements = Arrays.copyOf(elements, 2 * size + 1);
  29. }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement