package com.ykushch.algorithms.ch01.stack;

public class ResizingArrayStack<T> {
    private T[] arr;
    private int numberOfElems;
    private int capacity = 10;

    public ResizingArrayStack() {
        arr = (T[]) new Object[capacity];
    }

    public void push(T item) {
        if(isFull()) {
            resize(2 * arr.length);
        }
        arr[numberOfElems++] = item;
    }

    public T pop() {
        T item = arr[--numberOfElems];
        arr[numberOfElems] = null;
        if(numberOfElems > 0 && numberOfElems == arr.length / 4) {
            resize(arr.length / 2);
        }
        return item;
    }

    public boolean isEmpty() {
        return numberOfElems == 0;
    }

    public int size() {
        return numberOfElems;
    }

    private void resize(int max) {
        T[] temp = (T[]) new Object[max];
        // should be replaced with System.arraycopy for more performant method
        for(int i = 0; i < numberOfElems; i++) {
            temp[i] = arr[i];
        }
        arr = temp;
    }

    private boolean isFull() {
        return numberOfElems == arr.length;
    }
}

@@ -37,16 +37,44 @@
 stack;%0A%0A
+import java.util.Iterator;%0A%0A
 public c
@@ -99,16 +99,39 @@
 Stack%3CT%3E
+ implements Iterable%3CT%3E
  %7B%0A    p
@@ -333,16 +333,17 @@
       if
+ 
 (isFull(
@@ -542,16 +542,17 @@
       if
+ 
 (numberO
@@ -975,16 +975,17 @@
      for
+ 
 (int i =
@@ -1108,24 +1108,24 @@
  isFull() %7B%0A
-
         retu
@@ -1161,11 +1161,401 @@
 h;%0A    %7D
+%0A%0A    @Override%0A    public Iterator%3CT%3E iterator() %7B%0A        return new ReverseArrayIterator();%0A    %7D%0A%0A    private class ReverseArrayIterator implements Iterator%3CT%3E %7B%0A        private int i = numberOfElems;%0A%0A        public boolean hasNext() %7B%0A            return i %3E 0;%0A        %7D%0A%0A        public T next() %7B%0A            return arr%5B--i%5D;%0A        %7D%0A%0A        public void remove() %7B%0A        %7D%0A    %7D
 %0A%7D%0A

Add iterator capabilities