Hey guys,
Inspired from ArrayQueue class I extended Mosh’s solution and created this dynamic and all data Types queue that will work efficiently by using circular array.
@SuppressWarnings("unchecked")
public class ArrayQueue<T> {
private int front = 0;
private int rear = 0;
private int size = 1;
private int count = 0;
private T[] queue = (T[]) new Object[size];
public void enqueue(T item) {
manageSize();
queue[rear] = item;
rear = (rear + 1) % queue.length;
count++;
}
public void manageSize() {
int currentElement = 0;
if(isFull()){
size*=2;
var temp = (T[]) new Object[size];
for(int i = front; i < queue.length; i++){
temp[currentElement++] = queue[i];
}
for(int i = 0; i < front; i++) {
temp[currentElement++] = queue[i];
}
front = 0;
rear = currentElement;
queue = temp;
}
}
public T dequeue() {
if(!isEmpty()) {
var element = queue[front];
queue[front] = null;
front = (front+1) % queue.length;
count--;
return element;
}
return null;
}
public T peek() {
return queue[front];
}
public boolean isEmpty() {
return count == 0;
}
public boolean isFull() {
return count == size;
}
@Override
public String toString() {
return Arrays.toString(queue);
}
}