PriorityQueue屬於Java Collections Framework。PriorityQueue基於優先級堆,它是Queue接口的實現。當咱們須要一個Queue實現時,能夠使用這種數據結構,java
而且咱們須要根據每一個元素的優先級,以特定的排序順序來維護該集合的元素。它在JDK 1.5中引入安全
Java 之優先隊列要點數據結構
如下示例說明了如何使用Java PriorityQueue集合。ide
package com.javapapers.java; import java.util.Comparator; import java.util.PriorityQueue; public class PriorityQueueExample { public static void main(String[] args) { Comparator<String> queueComparator = new VowelComparator(); PriorityQueue<String> priorityQueue = new PriorityQueue<String>(10, queueComparator); priorityQueue.add("orange"); priorityQueue.add("fig"); priorityQueue.add("watermelon"); priorityQueue.add("lemon"); while (priorityQueue.size() != 0) { System.out.println(priorityQueue.remove()); } } }
此Comparator類用於肯定上述PriorityQueue的排序順序。函數
package com.javapapers.java; import java.util.Comparator; class VowelComparator implements Comparator<String> { @Override public int compare(String x, String y) { if (getVowelCount(x) < getVowelCount(y)) { return -1; } else if (getVowelCount(x) > getVowelCount(y)) { return 1; } return 0; } public int getVowelCount(String word) { int vowel = 0; for (int i = 0; i < word.length(); i++) { char chr = word.charAt(i); if (chr == 'a' || chr == 'A' || chr == 'e' || chr == 'E' || chr == 'i' || chr == 'I' || chr == 'o' || chr == 'O' || chr == 'u' || chr == 'U') vowel++; } return vowel; } }
PriorityQueue示例輸出:
fig lemon orange watermelonhttp://javapapers.com/java/search-file-using-nio/