Java - Queue Interface and Related Classes
Queue Interface
The Queue interface was added in J2SE 5.0 and has a Queue data structure with First-In, First-Out behavior. The Queue interface can delete only the first stored data item. Unlike other interfaces, it has methods such as offer() for storing data, remove() for deleting data, and element(), peek(), and poll() for retrieving data. Subclasses that implement the Queue interface include LinkedList and PriorityQueue.
Queue Methods
| Method | Description |
|---|---|
boolean add(E e) |
Puts an object into the Queue and returns true if it succeeds. |
boolean offer(E e) |
Puts an object into the Queue. |
E poll() |
Returns an object from the Queue, or null if it is empty. |
E peek() |
Returns the object at the bottom of the Queue, but does not remove it from the Queue. |
E remove() |
Returns the object at the bottom of the Queue and removes it from the Queue. |
PriorityQueue
PriorityQueue Example
package com.devkuma.tutorial.java.util.collection;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;
public class PriorityQueueClass {
public static void main(String[] args) {
Queue<String> queue = new PriorityQueue<String>();
queue.add("a");
queue.add("b");
queue.add("c");
queue.add("d");
queue.add("e");
System.out.println("head element: " + queue.element());
System.out.println("head peek : " + queue.peek());
System.out.println("iterating the queue elements:");
Iterator<String> itr = queue.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
System.out.println("head remove : " + queue.remove());
System.out.println("head poll : " + queue.poll());
System.out.println("after removing two elements:");
Iterator<String> itr2 = queue.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}
The execution result is as follows.
head element: a
head peek : a
iterating the queue elements:
a
b
c
d
e
head remove : a
head poll : b
after removing two elements:
c
d
e