//Written by Jory James

import java.util.NoSuchElementException;
import java.lang.Iterable;
import java.util.Iterator;

public class FixedLengthQueue<E> implements Iterable<E> {
    private Object[] arr = null;
    private int capacity = 0;
    private int size = 0;
    private int start = 0;

    public FixedLengthQueue(int cap){
        //if cap is negative
        capacity = (cap > 0) ? cap : 0;
        arr = new Object[capacity];
    }

    public int capacity(){ 
        return arr.length;
    }

    public int size(){
        return size;
    }

    public void add(E elm){
        if(elm == null){
            throw new NullPointerException();
        }
        if(size == capacity){
            throw new IllegalStateException();
        }
        arr[(start+size)%capacity] = elm;
        size++;
    }
    @SuppressWarnings("unchecked")
    public E remove(){
        if(size == 0) {
            throw new NoSuchElementException();
        }
        E elm = (E) arr[start];
        start = (start + 1)%capacity; //mod used to go to beginning of array
        size--;
        
        return elm;
    }
    @SuppressWarnings("unchecked")
    public Iterator<E> iterator(){
        return new Iterator<E>(){
            int next = start;
            int numReturned = 0;

            public boolean hasNext(){
                return (numReturned < size);
            }
            public E next(){
                E elm = (E) arr[next];
                next = (next + 1) % capacity;
                numReturned++;
                return elm;
            }
        };
    }
}
