public class CircularQueue<T> {
private int front;
private int rear;
private int size;
private T[] elements;
public CircularQueue(int capacity) {
elements = (T[]) new Object[capacity];
front = 0;
rear = 0;
size = 0;
}
public void enqueue(T element) {
if (size == elements.length) {
throw new IllegalStateException("Queue is full");
}
elements[rear] = element;
rear = (rear + 1) % elements.length;
size++;
}
public T dequeue() {
if (size == 0) {
throw new NoSuchElementException("Queue is empty");
}
T element = elements[front];
elements[front] = null;
front = (front + 1) % elements.length;
size--;
return element;
}
public T getFront() {
if (size == 0) {
throw new NoSuchElementException("Queue is empty");
}
return elements[front];
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
}
public class Main {
public static void main(String[] args) {
CircularQueue<Integer> queue = new CircularQueue<>(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.dequeue()); // Output: 1
System.out.println(queue.getFront()); // Output: 2
System.out.println(queue.isEmpty()); // Output: false
System.out.println(queue.size()); // Output: 2
}
}