此处包括一个泛型顺序队列抽象类,一个Integer型实现类,一个测试类。
实现了队列的以下功能:
1.队尾入队
2.队首出队
3.取队首
4.判空
5.求长度
6.删除队首元素
7.扩充长度
泛型顺序队列抽象类
Queue.java:
package queue;
import java.lang.reflect.Array;
import java.util.Arrays;
public abstract class Queue<T> {
protected int front;
protected int rear;
protected T[] arr;
private int maxSize;
public Queue(Class<T> componentType) {
this.front = 0;
this.rear = 0;
this.maxSize = 1024;
arr = (T[])Array.newInstance(componentType, this.maxSize);
}
public Queue(Class<T> componentType, int maxSize) {
this.front = 0;
this.rear = 0;
this.maxSize = maxSize;
arr = (T[])Array.newInstance(componentType, this.maxSize);
}
public int getSize() {
return this.rear - this.front;
}
public void expandMaxSize(int maxSize) {
Arrays.copyOf(arr, this.maxSize + maxSize);
this.maxSize += maxSize;
}
public void offer(T data) {
if(this.getSize() > this.maxSize || this.rear > this.maxSize) {
throw new IllegalArgumentException("new element will be out of limits.");
}
arr[this.rear++] = data;
}
public void remove() {
if(this.front == this.rear) {
throw new IllegalArgumentException("this queue is already empty");
}
this.front++;
}
public T peek() {
if(this.front == this.rear) {
throw new IllegalArgumentException("this queue is already empty");
}
return arr[this.front];
}
public T poll() {
if(this.front == this.rear) {
throw new IllegalArgumentException("this queue is already empty");
}
return arr[this.front++];
}
}
Integer型实现类
IntegerQueue.java:
package queue;
public class IntegerQueue extends Queue<Integer> {
public IntegerQueue() {
super(Integer.class);
}
public IntegerQueue(int maxSize) {
super(Integer.class, maxSize);
}
public void print(){
System.out.print("F-");
for(int i = this.rear - 1; i >= this.front; i--) {
System.out.print(arr[i] + "-");
}
System.out.println("R");
}
}
测试类
IntegerQueueDemo:
package queue;
public class IntegerQueueDemo {
public static void main(String[] args) {
IntegerQueue test = new IntegerQueue();
test.print();
System.out.println("size is: " + test.getSize());
System.out.println("================");
test.offer(8);
test.offer(14);
test.offer(5);
test.offer(3);
test.print();
System.out.println("size is: " + test.getSize());
System.out.println("================");
System.out.println("the element in front of queue: " + test.peek());
test.remove();
test.print();
System.out.println("size is: " + test.getSize());
System.out.println("the element in front of queue: " + test.peek());
System.out.println("================");
System.out.println("the fetched element: " + test.poll());
test.print();
System.out.println("size is: " + test.getSize());
System.out.println("the element in front of queue: " + test.peek());
}
}
输出结果:
F-R
size is: 0
================
F-3-5-14-8-R
size is: 4
================
the element in front of queue: 8
F-3-5-14-R
size is: 3
the element in front of queue: 14
================
the fetched element: 14
F-3-5-R
size is: 2
the element in front of queue: 5