1 publicclassTestMain {
2 publicstaticvoidmain(String[] args) {
3 PriorityQueue
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
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 }
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
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
10 for(Map.Entry
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
22 hashMap.put("1", "One");
23 hashMap.put("2", "Two");
24 hashMap