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:队列,先进先出
抛出异常 | 返回特殊值 | |
插入 | add(e) | offer(e) |
移除 | remove() | poll() |
检查 | element() | peek() |
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. 总结分类