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
}