Queue is a collection of objects. PriorityQueue is new with Java 5. The purpose of a PriorityQueue is to create a "priority-in, priority out" queue as opposed to a typical FIFO queue. A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case, the elements' ordering represents their relative priority.In priority Queue null value is not acceptable, NullPointerException is thrown.
Some important methods of PriorityQueue :-
To en-queue data elements : offer() and add() methods are used to en-queue elements in the queue. offer method insert element if possible otherwise return false. Add method insert element if possible otherwise IlligalStateExcepton is thrown.
To de-queue data elements : remove() and poll() methods are used to de-queue elements from the queue. Both method works to remove element from the queue but the order is depends on the condition. In case of remove method if element not present in the queue, exception is thrown but poll method returns null.
Get higher priority elements : element() and peek() method are used to get top priority element from the queue. Both elements are differ in their behavior. if queue is null than element method throws an exception (NoSuchMethodException) but in case of peek method null is returned.
Example :
public static void main(String[] args) {
PriorityQueue<String> queue=new PriorityQueue<String>();
//enqueue elements with add method.
queue.offer("second");
queue.offer("java");
queue.offer("fourth");
queue.offer("abb");
//enqueue elements with add method.
queue.add("seventh");
queue.add("wrap");
printMe(queue);
//check queue contains particular element.
if(queue.contains("second")){
System.out.println("queue contains 'second' elements.");
}
// dequeue top priority element with poll method.
System.out.println(" "+queue.poll());
// dequeue top priority element with remove method.
System.out.println(" "+queue.remove());
printMe(queue);
// use element method to get top priority element.
System.out.println(queue.element());
// remove elements.
queue.clear();
// use peek method to get top priority element.
System.out.println("top priority element : "+queue.peek());
}
public static void printMe(Queue queue){
if(queue.isEmpty()){
System.out.println("Queue is empty.");
}else{
System.out.println(queue);
}
}
Output:
No comments:
Post a Comment