package structures.stack;

import java.util.EmptyStackException;

import static java.util.Objects.requireNonNull;

public class ArrayStack<E> implements Stack<E> {

    private E[] elements;
    private int size = 0;

    @SuppressWarnings("unchecked")
    public ArrayStack() {
        this.elements = (E[]) new Object[2];
    }

    @SuppressWarnings("unchecked")
    public ArrayStack(int initialCapacity) {
        if (initialCapacity < 1) {
            throw new IllegalArgumentException("Initial capacity must be greater than 0");
        }

        this.elements = (E[]) new Object[initialCapacity];
    }

    @Override
    public E push(E element) {
        requireNonNull(element, "Null elements cannot be pushed onto a stack");

        if (isFull()) {
            expand();
        }

        elements[size++] = element;

        return element;
    }

    @Override
    public E pop() {
        assertNotEmpty();

        return elements[--size];
    }

    @Override
    public E peek() {
        assertNotEmpty();

        return elements[size - 1];
    }

    @Override
    public boolean isEmpty() {
        return size <= 0;
    }

    @Override
    public int size() {
        return this.size;
    }

    private void assertNotEmpty() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
    }

    private boolean isFull() {
        return size >= elements.length;
    }

    @SuppressWarnings("unchecked")
    private void expand() {
        int capacity = elements.length * 2;
        E[] temporary = (E[]) new Object[capacity];
        System.arraycopy(elements, 0, temporary, 0, elements.length);
        elements = temporary;
    }
}

@@ -735,33 +735,8 @@
 k%22);
-%0A%0A        if (isFull()) %7B
 %0A   
@@ -744,31 +744,28 @@
     
-    
 expand
-();%0A        %7D
+IfNecessary();
 %0A%0A  
@@ -1168,21 +1168,16 @@
  return 
-this.
 size;%0A  
@@ -1308,86 +1308,8 @@
  %7D%0A%0A
-    private boolean isFull() %7B%0A        return size %3E= elements.length;%0A    %7D%0A%0A
     
@@ -1362,21 +1362,60 @@
 d expand
+IfNecessary
 () %7B%0A
+        if (isFull()) %7B%0A    
         
@@ -1450,16 +1450,20 @@
 th * 2;%0A
+    
         
@@ -1514,16 +1514,20 @@
         
+  
+  
 System.a
@@ -1580,32 +1580,36 @@
 ength);%0A        
+    
 elements = tempo
@@ -1614,16 +1614,104 @@
 porary;%0A
+        %7D%0A    %7D%0A%0A    private boolean isFull() %7B%0A        return size %3E= elements.length;%0A
     %7D%0A%7D%0A

Refactor code into focused methods