發現本身的知識面水平實在是過低了,以前有這個概念,可是不知道Java已經實現了 PriorityQueue了,經別人的提醒,回來看了一下Thinking In Java,裏面的介紹確實很是詳細,並且代碼寫的很明朗。主要是一個實現了Comparable接口來對Priority進行控制。 java
In computer science, a priority queue is an abstract data type which is like a regular queue or stack data structure, but additionally, each element is associated with a 「priority」.
stack — elements are pulled in last-in first-out-order (e.g. a stack of papers)
queue — elements are pulled in first-in first-out-order (e.g. a line in a cafeteria)
priority queue — elements are pulled highest-priority-first (e.g. cutting in line, or VIP service). ide
A priority queue must at least support the following operations:
insert_with_priority: add an element to the queue with an associated priority
pull_highest_priority_element: remove the element from the queue that has the highest priority, and return it (also known as 「pop_element(Off)」, 「get_maximum_element」, or 「get_front(most)_element」; some conventions consider lower priorities to be higher, so this may also be known as 「get_minimum_element」, and is often referred to as 「get-min」 in the literature; the literature also sometimes implement separate 「peek_at_highest_priority_element」 and 「delete_element」 functions, which can be combined to produce 「pull_highest_priority_element」) this
下面就是其中的代碼: code
package com.bjwilly.test; import java.util.PriorityQueue; public class PriorityQueueTest extends PriorityQueue<PriorityQueueTest.TodoItem>{ static class TodoItem implements Comparable<TodoItem>{ private char primary; private int secondary; private String item; public TodoItem(String td,char pri,int sec){ primary = pri; secondary = sec; item = td; } @Override public int compareTo(TodoItem arg) { if(primary > arg.primary) return +1; if(primary == arg.primary) if(secondary > arg.secondary) return +1; else if(secondary == arg.secondary) return 0; return -1; } public String toString(){ return Character.toString(primary)+ secondary + ": " + item; } } public void add(String td,char pri,int sec){ super.add(new TodoItem(td,pri,sec)); } public static void main(String[] args) { PriorityQueueTest toDoList = new PriorityQueueTest(); toDoList.add("Empty trash",'C',4); toDoList.add("Feed dog",'A',2); toDoList.add("Feed bird",'B',7); toDoList.add("Mow lawn",'C',3); toDoList.add("Water lawn",'A',1); toDoList.add("Feed cat",'B',1); while(!toDoList.isEmpty()) System.out.println(toDoList.remove()); } }
輸出結果 接口
A1: Water lawn A2: Feed dog B1: Feed cat B7: Feed bird C3: Mow lawn C4: Empty trash