我正在尝试使用数组实现队列。(不使用内置的 Java Queue 函数)。但是,在测试时,数组只会在 size ==maxSize 时打印出来(因为数组的大小达到了 maxSize/容量)。除了在大小小于 maxSize 时不打印之外,测试用例通过。(它是一个双端队列,因此可以在前后添加元素)。有什么建议吗?
package vipQueueArray;
import java.util.NoSuchElementException;
public class vipQueue {
private Object[] array;
private int size = 0;
private int head = 0; // index of the current front item, if one exists
private int tail = 0; // index of next item to be added
private int maxSize;
public vipQueue(int capacity) {
array = new Object[capacity];
maxSize = capacity;
size = 0;
tail = maxSize - 1;
}
public Object Dequeue() {
if (size == 0) {
throw new NoSuchElementException("Cant remove: Empty");
}
Object item = array[head];
array[head] = null;
head = (head + 1) % array.length;
size--;
return item;
}
public void EnqueueVip(Object x) {
if (size == maxSize) {
throw new IllegalStateException("Cant add: Full");
}
array[tail] = x;
tail = (tail - 1) % array.length;
size++;
}
public void Enqueue(Object y) {
if (size == maxSize) {
throw new IllegalStateException("Cant add: Full");
}
array[head] = y;
head = (head + 1) % array.length;
size++;
}
public boolean isFull() {
return (size == maxSize);
}
public boolean isEmpty() {
return (size == 0);
}
}
public class Test{
public static void main(String[] args){
vipQueue Q = new vipQueue(2);
Q.Enqueue(4);
System.out.printf("->%d", Q.Dequeue());
} }