Queue Implementation in Java using Array
A Queue is a collection for holding elements prior to processing. It is a First In First Out (FIFO) data structure. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.
In the tutorial, we will see Queue Implementation in Java using Array
We have one to create a Queue with default size, the other one is used to specify the queue size.
We are using Object array so that we can hold any type of object in the Queue.
If the queue is full, the addElement() will throw an exception with the proper message.
If the queue is empty and we call the deleteElement () method, an exception is raised.
we are removing elements from the queue using deleteElement method.
package com.javacodestuffs.core.interfaces.queue;
class CustomQueue {
public static final int DEFAULT_SIZE = 6;
private Object data[];
private int index;
public CustomQueue() {
data = new Object[DEFAULT_SIZE];
}
public CustomQueue(int size) {
data = new Object[size];
}
public boolean isEmpty() {
return index == 0;
}
public void addElement(Object obj) throws Exception {
if (index == data.length - 1) {
throw new Exception("Queue is full. Dequeue some objects");
}
this.data[index] = obj;
this.index++;
}
public Object deleteElement() throws Exception {
if (isEmpty()) throw new Exception("Queue is empty");
Object obj = this.data[0];
for (int i = 0; i < this.index - 1; i++) {
data[i] = data[i + 1];
}
this.index--;
return obj;
}
}
public class CustomQueueTest {
public static void main(String[] args) throws Exception {
CustomQueue queue = new CustomQueue();
System.out.println("check queue is empty : " + queue.isEmpty());
queue.addElement("Hello");
queue.addElement("World");
queue.addElement("Welcome");
queue.addElement("to");
System.out.println(queue.deleteElement());
System.out.println(queue.deleteElement());
queue.addElement("Java");
queue.addElement("Programming");
System.out.println(queue);
//queue.addElement("Hello");
//queue.addElement("World");
}
}
output:
check queue is empty : true
Hello
World
com.java.CustomQueue@6d06d69c
If we uncomment last code we get the following error
Exception in thread "main" java.lang.Exception: Queue is full. Dequeue some objects
at com.java.CustomQueue.addElement(CustomQueueTest.java:27)
at com.java.CustomQueueTest.main(CustomQueueTest.java:66)
In this article, we have seen the Queue Implementation in Java using Array with examples. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment