A PriorityQueue is used when the objects are supposed to be processed based on priority instead of their arrival time.
A few important facts about PriorityQueue are as follows:
- It doesn't permit NULL objects.
- Non-comparable objects can not be used to form a priority queue.
Hierarchy of PriorityQueue class
It inherits methods from AbstractQueue and implements Serializable, Iterable, Collection, Queue interfaces.
Source code of Item.java
package com.t4b.test;
public class Item {
String name;
int id;
double price;
public Item(String name, int id, double price) {
super();
this.name = name;
this.id = id;
this.price = price;
}
@Override
public String toString() {
return "Item [name=" + name + ", id=" + id + ", price=" + price + "]";
}
}
Source code of TestMain.java
package com.t4b.test;
import java.util.Iterator;
import java.util.PriorityQueue;
public class TestMain {
public static void main(String[] args) {
PriorityQueue<Item> pq = new PriorityQueue<Item>();
pq.add(new Item("Apple", 1, 150.0));
pq.add(new Item("Grape", 2, 250.0));
pq.add(new Item("Mango", 3, 10));
pq.add(new Item("Pine Apple", 4, 100));
Iterator<Item> itr = pq.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.