0% found this document useful (0 votes)
92 views2 pages

Java Array-Based Queue Implementation

This class implements a queue data structure using an array. It contains methods for enqueue, dequeue, peek, and checks for empty and full that work on the circular array by tracking the front and rear indices and item count. A default size is used but a custom size can be provided to the constructor.

Uploaded by

Mouad Youssef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views2 pages

Java Array-Based Queue Implementation

This class implements a queue data structure using an array. It contains methods for enqueue, dequeue, peek, and checks for empty and full that work on the circular array by tracking the front and rear indices and item count. A default size is used but a custom size can be provided to the constructor.

Uploaded by

Mouad Youssef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

package com.github.YoussefMouad.DataStructures.

Queues;

public class ArrayQueue<T> implements IQueue<T> {


private final T[] items;
private int front;
private int rear;
private int count;

public ArrayQueue() {
this(10);
}

@SuppressWarnings("unchecked")
public ArrayQueue(int size) {
this.items = (T[])new Object[size];
}

@Override
public void enqueue(T item) {
if (isFull())
throw new IllegalStateException();

items[rear] = item;
// Circular array
rear = (rear + 1) % items.length;
count++;
}

@Override
public T dequeue() {
if (isEmpty())
throw new IllegalStateException();

T item = items[front];
items[front] = null;

front = (front + 1) % items.length;


count--;
return item;
}

@Override
public T peek() {
if (isEmpty())
throw new IllegalStateException();

return items[front];
}

@Override
public boolean isEmpty() {
return count == 0;
}

@Override
public boolean isFull() {
return count == items.length;
}
}

You might also like