I am implementing a queue using a circular array. I cannot figure out what is causing my array out of bounds exception. I clearly know what the error means etc, it is indicating that my array got out of range and in my case, an index of -1. I clearly know what the error means but I do not why I am getting it in my case. Here is the run-time exception I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Queue.dequeue(Queue.java:56)
at Queue.main(Queue.java:72)
And here is my queue implementation:
public class Queue<T>{
private int head, tail, size, capacity;
private T[] container;
private static final int DEFAULT_CAPACITY = 100;
public Queue(int n){
capacity = n;
head = -1;
tail = -1;
size = 0;
container = (T[]) new Object[capacity];
}
public Queue(){
this(DEFAULT_CAPACITY);
}
public boolean isEmpty(){
return size == 0;
}
public boolean isFull(){
return size == capacity;
}
public void enqueue(T item){
if(isFull()){
System.out.println("Queue Oveflow");
}
else{
tail = (tail + 1) % (capacity - 1);
size++;
container[tail] = item;
}
}
public T dequeue(){
if(isEmpty()){
System.out.println("Queue underflow");
System.exit(1);
return null;
}
else {
if(head == tail){
T item = container[head];
head = -1;
tail = -1;
size --;
return item;
}
else{
T item = container[head];
head = (head + 1) % (capacity -1);
size --;
return item;
}
}
}
public static void main(String[] args){
Queue myQueue = new Queue();
myQueue.enqueue(34);
myQueue.enqueue(38);
myQueue.enqueue(34);
System.out.println(myQueue.dequeue());
}
}