1. Map:key-value的映射關系
package context;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class TestMap {
public static void main(String[] args) {
Random random = new Random(47);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//計算0-29,每次數字出現的次數
for(int i=0; i<10000; i++) {
int key = random.nextInt(30);
Integer value = map.get(key);
map.put(key, value==null ? 1 : value+1);
}
System.out.println(map);
}
}
2.Queue:隊列,先進先出
抛出異常 | 傳回特殊值 | |
插入 | | |
移除 | | |
檢查 | | |
package context;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class TestQueue {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<Integer>();
Random r = new Random(47);
for(int i=0; i<10; i++) {
q.offer(r.nextInt(30));
}
System.out.println(q);
while(q.peek() != null) {
System.out.print(q.remove() + " ");
}
System.out.println();
}
}
a)priorityQueue:一個基于優先級堆的無界優先級隊列。優先級隊列的元素按照其自然順序進行排序,或者根據構造隊列時提供的
Comparator
進行排序,具體取決于所使用的構造方法。優先級隊列不允許使用
null
元素。依靠自然順序的優先級隊列還不允許插入不可比較的對象(這樣做可能導緻
ClassCastException
)。
此隊列的頭 是按指定排序方式确定的最小 元素。如果多個元素都是最小值,則頭是其中一個元素——選擇方法是任意的。隊列擷取操作
poll
、
remove
、
peek
和
element
通路處于隊列頭的元素。
package context;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
public class TestPriorityQueue {
public static void main(String[] args) {
List<Integer> ints = Arrays.asList(12, 2, 5, 3, 100, 56, 3, 11, 15, 66, 44, 13);
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(ints.size(), Collections.reverseOrder());
pq.addAll(ints);
pq.offer(33);
System.out.println("toString 未排序: " + pq);
while(pq.peek() != null) {
System.out.print(pq.remove() + " ");
}
System.out.println();
}
}
//output
toString 未排序: [100, 66, 56, 12, 44, 33, 3, 2, 11, 3, 15, 5, 13]
100 66 56 44 33 15 13 12 11 5 3 3 2
3. 總結分類
容器類常用方法(3)
