自定义对象,并实现Comparable接口。使用代码如下:
package tijava.container;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Queue;
class ToDoItem implements Comparable<ToDoItem> {
private char primary;
private int secondary;
private String item;
public ToDoItem(char primary, int secondary, String item) {
super();
this.primary = primary;
this.secondary = secondary;
this.item = item;
}
@Override
public int compareTo(ToDoItem o) {
if (this.primary > o.primary)
return +1;
if (this.primary == o.primary) {
if (this.secondary > o.secondary)
return +1;
else if (this.secondary == o.secondary)
return 0;
}
return -1;
}
public String toString() {
return Character.toString(primary) + this.secondary + " : " + this.item;
}
}
public class PriorityQueueDemo {
public static void main(String[] args) {
Queue<ToDoItem> q = new PriorityQueue<ToDoItem>();
q.add(new ToDoItem('C', 4, "Empty trash"));
q.add(new ToDoItem('A', 2, "Feed dog"));
q.add(new ToDoItem('B', 7, "Feed bird"));
q.add(new ToDoItem('C', 3, "Mow lawn"));
q.add(new ToDoItem('A', 1, "Water lawn"));
q.add(new ToDoItem('B', 1, "Feed cat"));
while (!q.isEmpty()) {
System.out.println(q.remove());
}
//reverseOrder
Queue<ToDoItem> q1 = new PriorityQueue<ToDoItem>(1,
Collections.reverseOrder());
q1.add(new ToDoItem('C', 4, "Empty trash"));
q1.add(new ToDoItem('A', 2, "Feed dog"));
q1.add(new ToDoItem('B', 7, "Feed bird"));
q1.add(new ToDoItem('C', 3, "Mow lawn"));
q1.add(new ToDoItem('A', 1, "Water lawn"));
q1.add(new ToDoItem('B', 1, "Feed cat"));
while (!q1.isEmpty()) {
System.out.println(q1.remove());
}
}
}
output:
A1 : Water lawn
A2 : Feed dog
B1 : Feed cat
B7 : Feed bird
C3 : Mow lawn
C4 : Empty trash
C4 : Empty trash
C3 : Mow lawn
B7 : Feed bird
B1 : Feed cat
A2 : Feed dog
A1 : Water lawn