In this example, you will see how to implements a priority queue in java.
Java priority queue implementation.
In this example, you will see how to implement a priority queue in java. The PriorityQueue() is constructor of PriorityQueue class. It creates a object of PriorityQueue with default size, and you can add value in this queue by using add(Element e) method. You can add value in any order but it will display in sorted order. There is also a method name iterator() that creates a iterator of this class. It is used for retrieving value of queue.
Code:
PriorityOueueExample.java
import java.util.Iterator; import java.util.PriorityQueue; public class PriorityOueueExample { public static void main(String[] args) { PriorityQueue obPriorQueue = new PriorityQueue(); obPriorQueue.add("B"); obPriorQueue.add("A"); obPriorQueue.add("C"); obPriorQueue.add("D"); obPriorQueue.add("E"); Iterator iterator = obPriorQueue.iterator(); System.out.println("Element of priority Queue."); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }Output:
Element of priority Queue. A B C D E |
Download this code.
[ 0 ] Comments