package edu.basejava.util;
public class Queue<V>
{
private static final int defaultSize = 10;
private int size;
private int front;
private int rear;
private V[] value;
public Queue()
{
this.setup(Queue.defaultSize);
}
public Queue(int size)
{
this.setup(size);
}
public void enqueue(V value)
{
if (this.isFull())
Log.error("队列容量已满");
else
{
this.rear=(this.rear+1)%this.size;
this.value[this.rear] = value;
}
}
public V dequeue()
{
if (this.isEmpty())
return null;
else
this.front = (this.front+1)%this.size;
return this.value[this.front];
}
public V peek()
{
return this.firstValue();
}
public V firstValue()
{
if (this.isEmpty())
return null;
else
return this.value[(this.front+1)%this.size];
}
public void clear()
{
this.front =this.rear= 0;
for (@SuppressWarnings("unused")
V v : this.value)
v = null;
}
public boolean isEmpty()
{
return this.front == this.rear;
}
public boolean isFull() // true if stack is full
{
return (this.front == (this.rear+1)%this.size);
}
@SuppressWarnings("unchecked")
private void setup(int size)
{
if (size < 0)
throw new IllegalArgumentException("错误的队列容量参数: " + size);
else
{
this.size = size+1;
this.value = (V[]) new Object[size+1];
}
}
}