Through this post we will learn the implementation of Queue Data- Structure in Java. Consider Queue as any real world queue. Consider a queue at any ticket counter. The person who joins the queue first gets served first.
Thus the first one to enter the queue is the first one to come out from the queue and unlike stack, queue is open at both ends. A Queue is a First-In-First-Out Data Structure.

Before we dig into the Queue implementation, let's first understand some basic terminology which will help us understand Queue's better.
Java-Queue-DataStructure

As you can see in the image above, Inserting a new element is done at the end of the queue and it is called as enqueue, while removing the element is done at the front of the queue and it is referred as dequeue.

We will do the Queue implementation in Java using Java Arrays.

import java.util.Arrays;

public class TheQueue {

    private String[] queueArray;
    private int queueSize;
    private int currentIndex = -1;

    TheQueue(int size) {
        queueSize = size;
        queueArray = new String[queueSize];
        Arrays.fill(queueArray, "-1");
    }

    public void enqueue(String newElement) {
        if (currentIndex + 1 < queueSize) {
            currentIndex++;
            queueArray[currentIndex] = newElement;
            System.out
                    .println("Enqueue : " + newElement + " is added to queue");
        } else {
            System.out.println("Queue is currently Full");
        }
    }

    public String dequeue() {
        if (currentIndex >= 0) {
            String toReturn = queueArray[0];
            System.out.println("Dequeue : " + queueArray[0]
                    + " is removed from the queue");
            for (int i = 0; i < queueArray.length - 1; i++) {
                queueArray[i] = queueArray[i + 1];
            }
            return toReturn;
        } else {
            System.out.println("Queue is currently empty");
            return "-1";
        }
    }

    public static void main(String args[]) {
        TheQueue queue = new TheQueue(10);
        queue.enqueue("Java");
        queue.enqueue("Programming");
        queue.enqueue("Language");
        queue.dequeue();
        queue.dequeue();
        queue.dequeue();
    }

}
Comments