Implement Queue Using Array
use a front and rear index tracker to locate the front and rear of the queue. Since the array size is fixed, this queue could only be updated when it is not full! And the index could be calculated using round-robin(when reach the end move to the front).
during the pop() , null the object after retrieving it
import java.util.Arrays;
public class CustomQueue<T> {
private T[] queue;
private int front;
private int rear;
private int size;
@SuppressWarnings("unchecked")
public CustomQueue(int length){
this.front = -1;
this.rear = -1;
this.size = length;
queue = (T[]) new Object[length];
}
public boolean isEmpty(){
return front == -1 && rear == -1;
}
public void push(T e){
int idx = (rear + 1) % size;
if(idx == front){
throw new IllegalStateException("Queue is full");
}
else if(isEmpty()){
front++;
rear++;
queue[rear] = e;
}
else{
rear = idx;
queue[rear] = e;
}
}
public T pop(){
T res = null;
if(isEmpty()) {
throw new IllegalStateException("Queue is empty, cant dequeue");
}
//only one element left
else if(front == rear){
res = queue[front];
queue[front] = null;
front = -1;
rear = -1;
}
else{
res = queue[front];
queue[front] = null;
front = (front + 1) % size;
}
return res;
}
@Override
public String toString() {
return "Queue [front=" + front + ", rear=" + rear + ", size=" + size
+ ", queue=" + Arrays.toString(queue) + "]";
}
}