Queue Implementation in Java Using ArrayList

In this post, we'll see how to use the ArrayList class to implement a Queue in Java. 

Understanding the Queue 

A Queue is a data structure that follows the First In First Out (FIFO) principle. This is the same logic that's applied when you stand in a line - the first person to get in is the first one to get out. 

Basic Operations: 

enqueue: Adds an item to the end of the queue. 

dequeue: Removes and returns the first item from the queue. 

isEmpty: Checks if the queue is empty. 

front: Peeks the first item without removing it. 

Java Implementation Using ArrayList

Let's implement our Queue:

import java.util.ArrayList;

public class QueueUsingArrayList<T> {

    private ArrayList<T> list = new ArrayList<T>();

    // Adds value at the end of available space.
    public void enqueue(T value) {
        list.add(value);
    }

    // Removes the first item 
    public T dequeue() {
        if (isEmpty()) {
            System.out.println("Queue is empty");
            return null;
        }
        return list.remove(0);
    }

    // Checks if the queue is empty
    public boolean isEmpty() {
        return list.isEmpty();
    }

    // Returns the first item without removing it.
    public T front() {
        return list.get(0);
    }
}

Testing the Queue:

public class Main {
    public static void main(String[] args) {
        QueueUsingArrayList<Integer> queue = new QueueUsingArrayList<>();

        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);

        System.out.println(queue.dequeue() + " dequeued from queue");
        System.out.println("Front item is " + queue.front());

        queue.enqueue(4);
        queue.enqueue(5);

        System.out.println(queue.dequeue() + " dequeued from queue");
    }
}

Output:

1 dequeued from queue
Front item is 2
2 dequeued from queue

Pros and Cons of Using ArrayList for Queue Implementation

Pros: 

Dynamic Size: Unlike arrays, ArrayLists are dynamic in size. This allows the queue to grow as needed. 

Underlying Functions: Many of the operations used for the queue are already implemented in ArrayList, simplifying the code. 

Cons: 

Performance: Each dequeue operation requires a shift in the elements of the ArrayList. Therefore, it's an O(n) operation, which may cause performance issues for large queues. 

Conclusion

Using ArrayList to implement a Queue in Java provides a dynamic and straightforward approach. However, for real-world applications with massive data, consider using Java's built-in Queue interface implemented by LinkedList for better performance. Always evaluate the requirements of your application before deciding on the data structure and implementation.

Comments