下面是代码实现:
import java.util.Arrays;
public class SequenceQueue {
//默认队列容量为10
private final int DEFAULT_CAPACITY = 10;
//底层数组
private Object[] elementData;
//容量
private int capacity;
//
private int front = 0;
private int rear = 0;
public SequenceQueue(){
this.capacity = DEFAULT_CAPACITY;
elementData = new Object[capacity];
}
public SequenceQueue(T element){
this();
elementData[0] = element;
rear ++;
}
public SequenceQueue(T element, int initCapacity){
this.capacity = initCapacity;
elementData = new Object[capacity];
elementData[0] = element;
rear ++;
}
//队列长度
public int length(){
return rear - front;
}
//判是否为空
public boolean isEmpty(){
return rear == front;
}
//向队列rear端插入元素
public void add(T element){
indexOutOfBoundsForAdd(rear);
elementData[rear ++] = element;
}
//向队列front端删除并返回 该元素
@SuppressWarnings("unchecked")
public T remove(){
noneElementForRemove();
T t = (T) elementData[front];
elementData[front ++] = null;
return t;
}
//element()返回但不删除front端元素
@SuppressWarnings("unchecked")
public T element(){
noneElementForRemove();
return (T) elementData[front];
}
//清空队列
public void clear(){
Arrays.fill(elementData, null);
front = 0;
rear = 0;
}
//toString 方法
public String toString(){
if(isEmpty()){
return "[]";
}
else{
StringBuilder sb = new StringBuilder("[");
for(int i = front; i < rear; i ++){
sb.append(elementData[i].toString() + ",");
}
return sb.toString().substring(0, sb.length() - 1) + "]";
}
}
private void indexOutOfBoundsForAdd(int index){
if(index > capacity - 1){
throw new IndexOutOfBoundsException("exception for SequenceQueue is filled:index of add is " + index);
}
}
private void noneElementForRemove(){
if(isEmpty()){
throw new IndexOutOfBoundsException("none any element in SequenceQueue!");
}
}
}
测试代码如下:
import com.yc.list.SequenceQueue;
public class SequenceQueueTest {
public static void main(String[] args) {
SequenceQueue queue = new SequenceQueue("aaa", 4);
queue.add("bbb");
queue.add("ccc");
queue.add("ddd");
System.out.println( "队列为: " + queue);
System.out.println();
String sElement = queue.element();
System.out.println( "队首为: " + sElement);
System.out.println( "队列为: " + queue);
System.out.println();
String sRemove = queue.remove();
System.out.println( "队首为: " + sRemove);
System.out.println( "队列为: " + queue);
System.out.println();
queue.add("eee");
}
}
运行结果为:
从上面的运行结果来看,当程序执行 String sRemove = queue.remove();这句后,队首的值 aaa 从队列移除,此时队列有3个元素,讲道理程序再执行add.("eee");是可行的,
但出现了上面的异常,这也是这个实现的代码的不足之处:出现“假满”现象。