Java PriorityQueue Class

  • PriorityQueue Class is one of the collection framework class which implements Queue, Serializable, Iterable and Collection interfaces.
  • It is using natural ordering to order then elements of PriorityQueue.Or elements will be ordered based on Comparator provided at queue construction time depending on which constructor is used.
  • PriorityQueue is based on a priority heap. Heap is tree based data structure where all the nodes of tree are in a specific order. Please read about Heap to learn how it works.
  • PriorityQueue does not allow non-comparable objects and it may throw ClassCastException if you will try to do so.
  • PriorityQueue does not allow null elements as well.
  • PriorityQueue implementation is not synchronized. So multiple threads should not access it concurrently.
Java PriorityQueue Class

Few methods which are used with PriorityQueue are as below.
  • boolean add(E e) : It will insert specified element in PriorityQueue.
  • void clear() : It will remove all elements from it to clear PriorityQueue.
  • boolean contains(Object o) : It will check and return true if specified element is available in PriorityQueue. Else it will return false.
  • boolean offer(E e) : It will insert specified element in PriorityQueue.
  • E peek() : It will return head(first) of the element from queue. If PriorityQueue is empty then it will return null.
  • E poll() : It will remove head(first) of the element from queue. If PriorityQueue is empty then it will return null.
  • boolean remove(Object o) : It will remove specified element's single instance from PriorityQueue if it is present.
  • int size() : It will return size of PriorityQueue.
  • Object[] toArray() : It will return elements array from queue.
  • <T> T[] toArray(T[] a) : It will return elements array from queue. The runtime type of the returned array is that of the specified array.
Below given example will show you how to use PriorityQueue methods.

PriorityQueueExample :
package JAVAExamples;

import java.util.PriorityQueue;

public class PriorityQueueExample {

 public static void main(String[] args) {
  //Create PriorityQueue.
  PriorityQueue q=new PriorityQueue();
  //Add items to PriorityQueue.
  q.add("one");
  q.add("two");
  q.add("three");
  q.add("four");
  q.add("five");
  q.add("six");
  q.add("seven");
  
  //Get size of PriorityQueue.
  System.out.println("Size of PriorityQueue is : "+q.size());
  
  //Print values of PriorityQueue.
  System.out.println("PriorityQueue elements are : "+q);
  
  //Get head of PriorityQueue.
  System.out.println("Head of PriorityQueue is : "+q.peek());
  
  //Remove head of PriorityQueue.
  q.poll();
  System.out.println("Now PriorityQueue elements are : "+q);  
 }
}

Output :
Size of PriorityQueue is : 7
PriorityQueue elements are : [five, four, seven, two, one, three, six]
Head of PriorityQueue is : five
Now PriorityQueue elements are : [four, one, seven, two, six, three]

No comments:

Post a Comment