要求实现java.util.Queue<E>。
1: 支持范型
2:支持固定size。当queue的满了之后插入元素的时候,最先入队的元素要自动remove。
------解决方案--------------------
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;
@SuppressWarnings("unchecked")
public class FixedSizeQueue<E> implements Queue<E> {
private Object[] elements;
private int capacity;
private int head;
private int tail;
private int size;
private int modCount;
public FixedSizeQueue(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException("Illegal Capacity: " + capacity);
elements = new Object[capacity];
this.capacity = capacity;
head = 0;
tail = (head - 1) % capacity;
size = 0;
}
@Override
public boolean add(E e) {
modCount++;
tail = (tail + 1) % capacity;
elements[tail] = e;
size = (size + 1) > capacity ? capacity : size + 1;
head = (tail + 1 + capacity - size) % capacity;
return true;
}
@Override
public E element() {
if (size == 0)
throw new NoSuchElementException();
E element = (E) elements[head];
return element;
}
@Override
public boolean offer(E e) {
return add(e);
}
@Override
public E peek() {
if (size == 0)