Queue Implementation in Java using Array With Examples

What is a Queue?

Queue is a special type of data structure, which is designed to hold elements before processing and process elements in a FIFO (first-in-first-out) manner. It’s part of java collections framework. In this tutorial, we will learn Queue implementation in Java using an array.

Basic Queue Functions

A Queue must have the following functions:

  • enqueue(obj) – insert element to the queue.
  • dequeue() – remove and return the least recent item from the queue.
  • isEmpty() – returns true if the queue is empty, else false.

Queue Implementation in Java

We can implement basic Queue functions using an array.

Here is the complete code to implement a Queue in Java.

Important Points

  • There are two constructors – one to create a Queue with default size, the other one is used to specify the queue size.
  • We are using a private integer variable “index” to manage the queue elements.
  • We are using an Object array so that we can hold any type of object in the Queue. We can use generics here too but I am avoiding that to keep the program simple.
  • If the queue is full, the enqueue() will throw an exception with proper message.
  • If the queue is empty and we call the dequeue() function, an exception is raised.

Implementation Limitations
The Queue methods are not synchronized and it’s not thread-safe. There is a chance of data inconsistency if you use this implementation in a multi-threaded environment.

Test Program to Check Queue Implementation

Let’s test our queue implementation with some calls to enqueue() and dequeue() functions.

Output:

If you uncomment the last two lines, the queue will get full and an exception will be raised.

Conclusion

A Queue is one of the simplest data structures. We can implement it using an array or a list.

By admin

Leave a Reply

%d bloggers like this: