publicclassArrayQueue<T>{
private T[]queue;
privatestaticint size =20; //队列容量
privateint front, rear; //队首、队尾下标
publicArrayQueue(){
queue=(T[])newObject[size];
front =0;
rear =0;
}
publicvoid add(T t) throws Exception
{
if((rear +1)% size == front)
thrownewException("over flow!");
rear =(rear +1)% size;
queue[rear]= t;
}
public T poll() throws Exception
{
if(front == rear)
thrownewException("under flow!");
front =(front +1)% size;
returnqueue[front];
}
public boolean isEmpty(){
return front == rear;
}
}
publicclassTest{
publicstaticvoid main(String[] args) throws Exception{
ArrayQueue<String> q =newArrayQueue<String>();
q.add("a");
q.add("b");
q.add("c");
q.add("d");
q.add("e");
q.add("f");
q.add("g");
q.add("h");
q.add("i");
q.add("j");
q.add("k");
q.add("l");
q.add("m");
while(!q.isEmpty()){
String temp = q.poll();
System.out.print(temp);
}
}
}
输出
abcdefghijklm