public class RingQueue<E> implements Queue<E> {
    private int limit;
    private int head = 0;	// beginning
    private int tail = 0;	// end
    private E[] data;
    public RingQueue(int limit) {
        this.limit = limit;
        this.data = (E[]) new Object[limit];
    }
    public boolean isEmpty() {  return this.head == this.tail;  }
    public E peek() {
        if (this.isEmpty()) {  throw new RuntimeException("eq");  }
        return this.data[this.head];
    }
    public E poll() {
        E result = this.peek();
        this.head = (this.head+1) % this.limit;
        return result;
    }
    public boolean offer(E elem) {
        int newTail = (this.tail+1) % this.limit;
        if (newTail == this.head) {
           return false;	// full
        }
        this.data[this.tail] = elem;
        this.tail = newTail;
        return true;
    }
    public static void main(String[] args) {
        Queue<Integer> queue = new RingQueue<Integer>(31);
        for (int i = 0; i < 100; i++) {
            queue.offer(i*i);
        }
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
        for (int i = 0; i < 7; i++) {
            queue.offer(i*i);
        }
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
        for (int i = 0; i < 7; i++) {
            queue.offer(i*i);
        }
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
        for (int i = 0; i < 7; i++) {
            queue.offer(i*i);
        }
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
        for (int i = 0; i < 7; i++) {
            queue.offer(i*i);
        }
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }
}

