1

On the collections framework Java provides the Queue , that can be mimicked by a List also. What would be a unique use of Queue that cannot be done by other collections framework ?

In fact the code snippets used by docs.oracle.com also point out that this is not a implementation that would necessarily require a Queue. What would be a real-time implementation of a Queue that can explain its applicability clearly ?.

https://docs.oracle.com/javase/tutorial/collections/interfaces/queue.html

[In the following example program, a queue is used to implement a countdown timer. The queue is preloaded with all the integer values from a number specified on the command line to zero, in descending order. Then, the values are removed from the queue and printed at one-second intervals. The program is artificial in that it would be more natural to do the same thing without using a queue, but it illustrates the use of a queue to store elements prior to subsequent processing.]

import java.util.*;

public class Countdown {
    public static void main(String[] args) throws InterruptedException {
        int time = Integer.parseInt(args[0]);
        Queue<Integer> queue = new LinkedList<Integer>();

        for (int i = time; i >= 0; i--)
            queue.add(i);

        while (!queue.isEmpty()) {
            System.out.println(queue.remove());
            Thread.sleep(1000);
        }
    }
}
Ali
  • 83
  • 1
  • 7
  • 1
    A possible real-life example could be [Message queue](https://en.wikipedia.org/wiki/Message_queue) – Naman Mar 12 '20 at 12:45
  • 1
    The `Queue` interface isn't very useful in reality, which is probably why they had a hard time coming up with good examples. The [BlockingQueue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html) interface is far more useful, as it provides inter-thread message passing (allowing e.g. producer-consumer type functionality). – Kayaman Mar 12 '20 at 12:59
  • Thank you Naman and Kayaman. That gives me a direction on what topics to devote more time on. – Ali Mar 12 '20 at 14:02
  • 1
    As discussed in [When to use LinkedList over ArrayList in Java?](https://stackoverflow.com/q/322715/2711488), you will rarely use `LinkedList` in practice. When you need a `List`, you will most often use `ArrayList`, when you need a `Queue` or `Deque` (which can also serve as a stack), you will most often use `ArrayDeque`. You wouldn’t use `ArrayList` as a `Queue`, as removing from the front would be highly inefficient. The `ArrayDeque`, on the other hand, doesn’t offer the direct access methods of a `List`. So you have to choose depending on the use case then. – Holger Mar 12 '20 at 17:24

0 Answers0