PriorityQueue类php
优先队列无论你按照什么顺序插入元素,出队列的时候元素都是按顺序输出的。也就是每次调用remove的时候,都返回当前队列中最小的元素。而后队列中的元素不是维持排序状态的,若是你迭代这个优先队列中的元素,会发现他们不是排好序的。css
优先队列使用堆数据结果,堆是一种自我调整的二叉树,对树的add与remove操做可让最小的元素移动到树的根部。html
使用优先队列的典型示例是任务调度,每一个任务都有一个优先级,任务以随机顺序添加到队列中。每当启动一个新的任务时,都将优先级最高的任务从队列中取出进行处理java
PriorityQueue<GregorianCalendar> pq = new PriorityQueue<>();
pq.add(new GregorianCalendar(1906, Calendar.DECEMBER, 9));
pq.add(new GregorianCalendar(1815, Calendar.DECEMBER, 10));
pq.add(new GregorianCalendar(1903, Calendar.DECEMBER, 3));
pq.add(new GregorianCalendar(1910, Calendar.JUNE, 22));
System.out.println("Iterating over elements...");
for (GregorianCalendar date : pq)
{
System.out.println(date.get(Calendar.YEAR));
}
System.out.println("Removing elements...");
while (!pq.isEmpty())
{
System.out.println(pq.remove().get(Calendar.YEAR));
}
输出结果:node
Iterating over elements... 1815 1906 1903 1910 Removing elements... 1815 1903 1906 1910
Java类库提供两种maps实现:HashMap与TreeMap,他们都实现了Map接口。
哈希(hash)函数与比较函数仅应用于map的key上, map的value只是key的一个关联, value不会进行哈希与比较。nginx
使用HashMap存储元素:git
Map<String, Employee> staff = new HashMap<>(); // HashMap implements Map
Employee harry = new Employee("Harry Hacker");
staff.put("987-98-9996", harry);
. . .
Set<K> keySet() Collection<K> values() Set<Map.Entry<K, V>> entrySet()
迭代全部map中的key:github
Set<String> keys = map.keySet();
for (String key : keys)
{
do something with key
}
迭代map中的key和value:web
for (Map.Entry<String, Employee> entry : staff.entrySet())
{
String key = entry.getKey();
Employee value = entry.getValue();
do something with key, value
}