- The AP subset requires students to know the following methods of the
java.util.PriorityQueue
:
void add(Object item)
//Inserts item into the PriorityQueue.
boolean isEmpty()
//Returns true if the PriorityQueue has no //elements.
Object peek()
//Returns the next element without removing it.
Object remove()
//Returns and removes the next element according
//to its given priority. The priority is
//determined by the compareTo() method. Therefore
//all elements added to the PriorityQueue must
//implement the Comparable() interface. The
//element with the lowest value in CompareTo()
//will be returned.
- To declare a reference variable for a
PriorityQueue
, do the following.
PriorityQueue <ClassName> myStack =
new PriorityQueue<ClassName> ();
- Here is a short example showing how to create, populate, and deconstruct a PriorityQueue.
PriorityQueue <Integer> q = new PriorityQueue <Integer> ();
for(int i = 5; i >= 1; i--){
q.add(i);
}
for(Integer temp : q){
System.out.println(temp);
}
while(!q.isEmpty()){
System.out.println(q.remove());
}
Output:
1
2
3
4
5
1
2
3
4
5
In this example, the output prints from one to five twice. This is because the PriorityQueue will insert the elements it receives in the order of their priority rather than the order that they are received. Note: The Integer class implements Comparable.