Queue implementation classes in Java

Here are the three main implementation classes of the Java Queue interface:

1. LinkedList:

The LinkedList class implements the Queue interface, making it an easy-to-use queue. It provides all the methods of the Queue interface and allows null elements. The LinkedList class provides constant-time performance for adding and removing elements from both ends of the queue, making it a good choice for implementing a queue.

Example:

                
    Queue<String> queue = new LinkedList<>();
    queue.offer("A");
    queue.offer("B");
    queue.offer("C");
    String element = queue.peek();
    System.out.println("Head element: " + element);
                
            

Output:

                
    Head element: A
                
            

2. PriorityQueue:

The PriorityQueue class implements the Queue interface, but it orders the elements according to their natural order or using a Comparator provided at the time of creation. The elements of a PriorityQueue are ordered in such a way that the smallest element is always at the head of the queue. The PriorityQueue class provides logarithmic time performance for adding and removing elements, making it a good choice for implementing a priority queue.

Here is the example of PriorityQueue:

                
    Queue<String> queue = new PriorityQueue<>();
    queue.offer("A");
    queue.offer("B");
    queue.offer("C");
    String element = queue.peek();
    System.out.println("Head element: " + element);
                
            

Output:

                
    Head element: A
                
            

3. ArrayDeque:

The ArrayDeque class implements both the Queue and Deque interfaces, which means it can be used as a queue or as a stack. It provides constant-time performance for adding and removing elements from both ends of the queue, making it a good choice for implementing a queue. The ArrayDeque class does not allow null elements.

Here is the example of ArrayDeque:

                
    Queue<String> queue = new ArrayDeque<>();
    queue.offer("A");
    queue.offer("B");
    queue.offer("C");
    String element = queue.peek();
    System.out.println("Head element: " + element);
                
            

Output:

                
    Head element: A
                
            

Note that all of these implementation classes can be used to create queues that follow the First-In-First-Out (FIFO) principle. However, the LinkedList and ArrayDeque classes can also be used as double-ended queues (Deque), while the PriorityQueue class is used for priority queues where elements are ordered based on their priority.