java tutorial - Java Queue Interface - java programming - learn java - java basics - java for beginners
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed first and last element is removed at last.
Queue Interface declaration
Methods of Java Queue Interface
|boolean add(object)||It is used to insert the specified element into this queue and return true upon success.|
|boolean offer(object)||It is used to insert the specified element into this queue.|
|Object remove()||It is used to retrieves and removes the head of this queue.|
|Object poll()||It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.|
|Object element()||It is used to retrieves, but does not remove, the head of this queue.|
|Object peek()||It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.|
The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO manner. It inherits AbstractQueue class.
PriorityQueue class declaration
Let's see the declaration for java.util.PriorityQueue class.
Java PriorityQueue Example
Java PriorityQueue Example: Book
Let's see a PriorityQueue example where we are adding books to queue and printing all the books. The elements in PriorityQueue must be of Comparable type. String and Wrapper classes are Comparable by default. To add user-defined objects in PriorityQueue, you need to implement Comparable interface.