Sure, here's a basic implementation of a queue in Java using an array:
public class Queue {
private int maxSize; // Maximum size of the queue
private int[] queueArray;
private int front; // Front of the queue
private int rear; // Rear of the queue
private int currentSize; // Current size of the queue
// Constructor to initialize the queue
public Queue(int size) {
maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1;
currentSize = 0;
}
// Method to check if the queue is empty
public boolean isEmpty() {
return currentSize == 0;
}
// Method to check if the queue is full
public boolean isFull() {
return currentSize == maxSize;
}
// Method to get the current size of the queue
public int size() {
return currentSize;
}
// Method to insert an element into the queue
public void enqueue(int item) {
if (isFull()) {
System.out.println("Queue is full. Cannot enqueue " + item);
return;
}
rear = (rear + 1) % maxSize;
queueArray[rear] = item;
currentSize++;
}
// Method to remove an element from the queue
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue.");
return -1;
}
int removedItem = queueArray[front];
front = (front + 1) % maxSize;
currentSize--;
return removedItem;
}
// Method to view the front element of the queue
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty. No element to peek.");
return -1;
}
return queueArray[front];
}
public static void main(String[] args) {
Queue queue = new Queue(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
System.out.println("Front element: " + queue.peek());
System.out.println("Dequeued element: " + queue.dequeue());
System.out.println("Front element after dequeue: " + queue.peek());
}
}
This implementation includes methods for checking if the queue is empty or full, getting the current size of the queue, enqueueing elements, dequeueing elements, and peeking at the front element of the queue. It's a basic implementation and doesn't include error handling for all scenarios.