标签:实例化 pap term range 1.5 for override frame 方法
PriorityQueue属于Java Collections Framework。PriorityQueue基于优先级堆,它是Queue接口的实现。当我们需要一个Queue实现时,可以使用这种数据结构,
并且我们需要根据每个元素的优先级,以特定的排序顺序来维护该集合的元素。它在JDK 1.5中引入
Java 之优先队列要点
以下示例说明了如何使用Java PriorityQueue集合。
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
watermelon
http://javapapers.com/java/search-file-using-nio/
标签:实例化 pap term range 1.5 for override frame 方法
原文地址:http://www.cnblogs.com/JavaBlackHole/p/7675159.html