Java和C++在细节上的差异(四)(九)

2014-11-24 02:04:05 · 作者: · 浏览: 9
的时候,总是取出队列中最小(优先级最高)的元素。该集合内部是通过"堆"的数据结构实现的,该结构只有第一个元素(头部元素)保证为该集合中最大的或最小的元素,其余元素没有固定的顺序,但是当集合有新的对象从尾部插入或是从头部取出时,集合内部的相关元素会进行比较的比较最终再次决定出谁是最大或最小的元素作为头部元素。在JDK提供的classes中Timer是通过该数据结构实现的,从而保证了Timer每次获取任务时都是最应该被调度的TimerTask,见如下代码:

1 publicclassTestMain {
2 publicstaticvoidmain(String[] args) {
3 PriorityQueue pq = newPriorityQueue();
4 pq.add("1");
5 pq.add("6");
6 pq.add("4");
7 pq.offer("5");
8 pq.offer("3");
9 pq.offer("2");
10 pq.offer("7");
11 //以下输出将以无序的结果输出
12 System.out.println(pq);
13 //以下输出将以有序的结果输出
14 while(pq.peek() != null) {
15 String str = pq.poll();
16 System.out.println(str);
17 }
18 intinitCapacity = 20;
19 PriorityQueue pq1 = newPriorityQueue(initCapacity,
20 newComparator() {
21 publicintcompare(TestComparator t1, TestComparator t2) {
22 returnt1.getID() - t2.getID();
23 }
24 });
25 pq1.offer(newTestComparator(1));
26 pq1.offer(newTestComparator(6));
27 pq1.offer(newTestComparator(4));
28 pq1.offer(newTestComparator(5));
29 pq1.offer(newTestComparator(3));
30 pq1.offer(newTestComparator(2));
31 pq1.offer(newTestComparator(7));
32 System.out.println("The following is for TestComparator.");
33 System.out.println(pq1);
34 while(pq1.peek() != null) {
35 intid = pq1.poll().getID();
36 System.out.println(id);
37 }
38 }

39 }
40
41 classTestComparator {
42 publicTestComparator(intid) {
43 _id = id;
44 }
45 publicintgetID() {
46 return_id;
47 }
48 publicString toString() {
49 returnInteger.toString(_id);
50 }
51 privateint_id;
52 }

9. HashMap:其内部数据结构的逻辑类似于HashSet,只是Map存储的都是key/value的键值映射关系,key相当于HashSet中的对象,value只是附着于key的对象,使用者一般都是通过key的值去HashMap中搜索,找到并返回该key以及相关联的value,其内部实现机制可参考HashSet。在接口方面主要的不同点是Map对象可以生成3个集合的视图(仅仅是视图,没有对象copy,视图的底层容器仍然来自于原映射对象集合,如果在其中任意视图或原集合删除和添加数据都会及时反应与其他视图和映射集合)。该规则同样适用于TreeMap。见以下常用代码示例:

1 publicstaticvoidshowGetAndPut() {
2 HashMap hm = newHashMap();
3 hm.put("A", newDouble(3.34));
4 hm.put("B", newDouble(1.22));
5 hm.put("C", newDouble(1.00));
6 hm.put("D", newDouble(9.22));
7 hm.put("E", newDouble(-19.08));
8 //随机的获取HashMap中的数据
9 Set> set = hm.entrySet();
10 for(Map.Entry me : set) {
11 System.out.print(me.getKey() + ": ");
12 System.out.println(me.getValue());
13 }
14 doublebalance = hm.get("A");
15 //输出1003.34
16 hm.put("A", balance + 1000);
17 System.out.println(hm.get("A"));
18 }
19
20 publicstaticvoidshowContainsAndRemove() {
21 HashMap hashMap = newHashMap();
22 hashMap.put("1", "One");
23 hashMap.put("2", "Two");
24 hashMap