日期:2014-05-20 浏览次数:20892 次
package graph.utils;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class FixedRingBuffer<Item> implements Iterable<Item> {
private Item[] q; // queue elements
private int N = 0; // number of elements on queue
private int first = 0; // index of first element of queue
private int last = 0; // index of next available slot
/**
* Initializes an empty queue.
*/
public FixedRingBuffer() {
// cast needed since no generic array creation in Java
this(2);
}
public FixedRingBuffer(int capacity){
q = (Item[]) new Object[capacity];
}
/**
* Is this queue empty?
* @return true if this queue is empty; false otherwise
*/
public boolean isEmpty() {
return N == 0;
}
/**
* Returns the number of items in this queue.
* @return the number of items in this queue
*/
public int size() {
return N;
}
public boolean hasCapacity(){
return !(N == q.length);
}
/**
* Adds the item to this queue.
* @param item the item to add
*/
public void enqueue(Item item) {
if(!hasCapacity()) throw new ArrayIndexOutOfBoundsException("not enough room for the item");
q[last++] = item; // add item
if (last == q.length) last = 0; // wrap-around
N++;
}
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = q[first];
q[first] = null; // to avoid loitering
N--;
first++;
if (first == q.length) first = 0; // wrap-around
// shrink size of array if necessary
//if (N > 0 && N == q.length/4) resize(q.length/2);
return item;
}
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return q[first];
}
/**
* Returns an iterator that iterates over the items in this queue in FIFO order.
* @return an iterator that iterates over the items in this queue in FIFO order