Java Collection: PriorityQueue - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Java Collection: PriorityQueue

Share This

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:

  1. It doesn't permit NULL objects.
  2. 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 + "]";
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Source code of TestMain.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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());
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.