日期:2014-05-20 浏览次数:20760 次
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)