DEV Community

Hector de Isidro
Hector de Isidro

Posted on • Updated on

To Queue or not to Queue?

That should not be a question

Waiting In Line To See Star Wars: 1977–2000

No one likes to stand in line¹. Most people hate to waste their time queuing up. We spend an average of 6 months of our adult lives waiting our turn — almost 3 days a year. There are books about queues. Documentaries². Even academic experts in queues. But then, when we are coding, we often forget to use queues and end up messing around with lists instead.

All things work better when you use the right tool.

FIFO or LIFO1!!!

A queue in a supermarket is FIFO. The way we usually stack boxes is LIFO. FIFO stands for “First In, First Out”³. LIFO is the acronym for “Last In, First Out”. That’s it.


I used draw.io to draw this diagram. Awesome tool!

When implementing FIFO queues we usually use add, peek (returns, but does not remove, the head of the queue) and poll (returns and removes the head of the queue) methods, while we refer to them, respectively, as push, peek and pop in **LIFO **stacks.

The STACK, the QUEUE and the DEQUE

In a stack we can only add and remove elements from one end (LIFO), in a queue we add elements to one end and remove them from the other (FIFO) and, joining those two worlds we have the deque (aka “Double Ended Queue”) where we can add and remove elements from both ends. None of them allows random access to the elements.



In JAVA you should use deque to model a stack because the Stack class is considered obsolete (it extends the Vector class and inherits all its methods, making it possible to break the LIFO principle).

So, don’t reinvent the wheel⁴.

This article was originally published on Medium


[1] Ok, there are some weird exceptions:facepalm:
[2] There is always an alternative https://www.youtube.com/watch?v=ZyNz8UHHrxE (in Spanish):wink:
[3] Some people know it as FCFS (“First Come, First Served”)
[4] And remember to give LolaMarket a chance. Awesome service!


External links 👀

Top comments (0)