Queue in Java | Priority Queue Java | Java Queue FIFO – Part 2
Queue in Java chapter is an immediate successor of Java Collections Framework that we had seen earlier. Make sure you have completely understood List before proceeding to learn about Java Queue FIFO.
As per the hierarchy that we have seen for JCF, queue interface stands as our next topic.
Queue in Java
Generally speaking, what do you really mean by queue? A line, right? You would know, now wouldn’t you? How many times in your life have you been forced to stand in a barely moving queue. So what was it like? Not the experience. I know it must have sucked. I mean the behaviour of the queue?
If you might remember the first person to enter the queue is the first to get out too once his/her job is done. Such a kind of setup of “first in first out” is also popularly abbreviated as FIFO. So with that, we have established that a queue follows a FIFO.
A Queue in Java is no different. It follows FIFO meaning it orders elements on the basis of first in first out. So the first element is removed first and the last element gets removed last.
Queue Interface
As you might have already guessed Queue in Java is an Interface that extends Collection Interface. There are only six methods in here and they are:
- add(Object e)
- offer(Object e)
- element()
- peek()
- poll()
- remove()
The last four methods namely, element(), peek(), poll() and remove() more or less do the same thing – retrieves the head of the queue. Out of these four, the last two namely: poll() and remove() also remove the head from the queue.
NOTE: A queue doesn’t allow the insertion of null elements. Duplicates are allowed in queue.
Since we cannot instantiate an interface, we will use one of its inheriting classes to see all the aforementioned methods in an example. There are two classes that implement Queue interface and they are:
- LinkedList
- PriorityQueue
So writing:
Queue q = new LinkedList();
or
Queue q = new PriorityQueue();
would be both correct.
One of the crucial classes that inherit Queue Interface’s methods is PriorityQueue which is our next topic.
Priority Queue Java Class
Priority Queue Java or PriorityQueue Class is one of those classes that implement Queue interface. It extends AbstractQueue class which in turn implements Queue to rake in its benefits.
Here’s a hierarchical diagram explaining things in a much better way:
PriorityQueue Class has the facility to use Queue in Java. However, surprisingly it does not order around elements in FIFO manner. It orders elements based on element’s natural ordering or based on the supplied comparator.
PriorityQueue Constructors and Methods
Here are the constructors of PriorityQueue that you could use:
- PriorityQueue()
- PriorityQueue(Collection c)
- PriorityQueue(int capacity)
- PriorityQueue(int capacity, Comparator comparator)
- PriorityQueue(PriorityQueue p)
- PriorityQueue(SortedSet s)
The methods of PriorityQueue class you can use are:
- add(Object e)
- clear()
- comparator()
- contains(Object o)
- iterator()
- offer(Object e)
- peek()
- poll()
- remove(Object o)
- size()
- toArray()
- toArray(T[] a)
Priority Queue Java Example
Here an example would be helpful:
PriorityQueue<Integer>q = new PriorityQueue<Integer>(5); q.add(23); q.add(1); q.add(3); q.add(7); q.offer(6); // does the same thing as add System.out.println(q);
Notice here offer() method of Queue Interface does the same thing as add(). If you run the program above, you will get:
[1, 6, 3, 23, 7]
As you can see the elements are ordered as per their natural ordering. It doesn’t follow any FIFO here.
Let’s see what other methods we can put up in there to see what they do. Append the following code to the above code:
System.out.println("Head of the queue: " + q.poll()); System.out.println(q); q.clear(); System.out.println(q);
Poll as we had learned earlier helps in extracting the head of the queue by removing it. The method clear() will simply remove everything from the list. Here’s the result you will get now:
[1, 6, 3, 23, 7] Head of the queue: 1 [3, 6, 7, 23] []
As you have noticed already that the ordering is kind of naturally done for you. It might be cumbersome for you. You could choose to use a method called comparator() to provide your own ordering. If there’s no comparator provided and the ordering is innate, it will give you a result as null. Like if you augment the following in the above code:
Comparator c = q.comparator(); System.out.println(c);
If you run it now you will get:
null
Other methods are pretty much the same that we had seen in ArrayList and LinkedList earlier. So I am not going to describe them all over again. Of course, you can always go back to see what does what.
Deque Interface
Moving on to the main course now. It is the Deque (pronounce it as Deck because that’s how the cool kids do) interface. It is a double ended queue. That’s what it stands for too. What is a double ended queue, you ask?
Well it is a queue that allows us to push elements from both ends. That didn’t sound right.
I mean take a look at this diagram and see for yourself:
Here you can enter an element from front or from the rear end. Also, you can order something to be removed from either the front side or the rear.
So deque interface is basically a linear collection that allows element insertion and removal from both its ends. It is different from queue in java in that respect.
When we will see the example things would be much clearer.
Methods of Deque
Deque methods can be classified under three different categories.
- Insert – addFirst(), offerFirst(), addLast(), offerLast()
- Remove – removeFirst(), pollFirst(), removeLast(), pollLast()
- Retrieve – getFirst(), peekFirst(), getLast(), peekLast()
So to list all of its methods down here:
- add(Object e)
- addFirst()
- offerFirst()
- addLast()
- offerLast()
- removeFirst()
- pollFirst()
- removeLast()
- pollLast()
- getFirst()
- peekFirst()
- getLast()
- peekLast()
- contains(Object o)
- descendingIterator()
- element()
- iterator()
- offer(Object e)
- peek()
- poll()
- pop()
- push(Object e)
- remove()
- remove(Object o)
- removeFirstOccurrence(Object o)
- removeLastOccurrence(Object o)
- size()
Since we cannot instantiate an interface we must use some concrete classes to do that for us. The following two classes come in handy:
- LinkedList
- ArrayDeque
So choosing to use either:
Deque d = new LinkedList();
or
Deque d = new ArrayDeque();
would be both fine.
LinkedList is something we have already seen. We will focus on the second kind.
ArrayDeque in Java
ArrayDeque is a class that implements Deque. It gives you the ability to incorporate resizable-arrays. It extends AbstractCollection class.
Here’s its hierarchical diagram to make you understand where it stands in Java Collections Framework.
You can add and remove elements from both sides since it implements deque. It doesn’t allow null elements as was the case with List. Duplicates are fine. It is also not thread safe.
ArrayDeque is faster than LinkedList and has no capacity restrictions.
Constructors and Methods of ArrayDeque
Let’s take a look at its constructors:
- ArrayDeque()
- ArrayDeque(Collection c)
- ArrayDeque(int numElements)
Here are the methods that it uses:
- add(Object e)
- addFirst()
- addLast()
- clear()
- clone()
- contains(Object o)
- descendingIterator()
- element()
- getFirst()
- getLast()
- isEmpty()
- iterator()
- offer(Object e)
- offerFirst()
- offerLast()
- peek()
- peekFirst()
- peekLast()
- poll()
- pollFirst()
- pollLast()
- pop()
- push(Object e)
- remove()
- remove(Object o)
- removeFirst()
- removeFirstOccurrence(Object o)
- removeLast()
- removeLastOccurrence(Object o)
- size()
- toArray()
- toArray(T[] a)
An example here would be awesome now:
ArrayDeque<Integer>d = new ArrayDeque<Integer>(); d.add(23); d.add(1); d.addFirst(3); d.add(7); d.addLast(3); System.out.println(d); System.out.println("Head of the queue: " + d.poll()); System.out.println(d); System.out.println(d.peekFirst()); System.out.println(d.getLast());
Print the above and you will get:
[3, 23, 1, 7, 3] Head of the queue: 3 [23, 1, 7, 3] 23 3
I think all the other methods we have seen one way or the other. Rest are pretty simple to understand. Experiment away soldier!
We are yet to find out about Set, that’s one of the most crucial sections of JCF. Yes there’s going to be a Part 3 for this punishing section and it is going to be all about Set.
You can’t rush into things, can you?
Farewell peeps.
2 Responses
[…] In Part 2 of this section we will see Queue. […]
[…] here for the first time I advise you to check out Java Collections Framework – List and Queue to keep things in order which are like the part 1 and part 2 of […]