I am trying to implement a Queue with an array. (Not using the built in Java Queue functions). However, when tested, the array will only print out when size ==maxSize (as in the size of the array reached the maxSize/capacity). Other than not printing when the size is less than maxSize, the test cases pass. (It is a double ended Queue, so elements can be added to the front and back). Any advice?
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());
} }
EnqueueandDequeueboth usehead. I would expect that from a stack, not from a queue.dequeuetakes care of it in a very elegant way (modulo).