how to create a Priority Queue using collections in java
Previous | Home | Next |
In this example we are going to create a PriorityQueue.
For creating a PriorityQueue first of all we have to import the java.util package in which the java.util.PriorityQueue class is defined. In this example we have created a class named CollectionsExample in which we created an object of the PriorityQueue and added some elements to the queue.
We have created a PriorityQueue object pq by using the default constructor defined in the java.util.PriorityQueue. This queue contains all the elements of integer types.
For adding the elements to the PriorityQueue we have used the add(Obejct obj) method on the object of the PriorityQueue. This method is having the general syntax as,
boolean add(Object obj)
This method adds the specified object to the current PriorityQueue.
In this example we have crreated a PriorityQueue by using the java.util.PriorityQueue class. We have created an object of this class by using its default constructor. Then we have added some elements to this queue by using the add(Object obj) method on its object. Finally we have displayed the contents of the created PriorityQueue.
package r4r.co.in;
import java.util.*;
public class CollectionsExample {
/**
* @param args
*/
public static void main(String[] args) throws NullPointerException, ClassCastException
{
// TODO Auto-generated method stub
try
{
PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); // creating a PriorityQueue of Integer type
pq.add(1); // adding element to the queue
pq.add(2);
pq.add(3);
pq.add(4);
pq.add(5);
System.out.println("The contents of the PriorityQueue are: "+pq); // displaying the elements of the queue
}
catch(NullPointerException e)
{
e.printStackTrace();
}
catch(ClassCastException e)
{
e.printStackTrace();
}
}
}
The output of the above example is:
The contents of the PriorityQueue are: [1, 2, 3, 4, 5]
Previous | Home | Next |