25 System.out.println(hashMap.containsValue("Three"));
26 String str = hashMap.remove("2");
27 System.out.println("old value of 2 = " + str);
28 System.out.println(hashMap.containsValue("Two"));
29 Set
30 st.remove("1");
31 System.out.println("The size is equal to " + hashMap.size());
32 System.out.println(hashMap.containsKey("3"));
33 }
34 /* 结果如下
35 true
36 old value of 2 = Two
37 false
38 The size is equal to 1
39 true */
40
41 publicstaticvoidshowIterator() {
42 String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter"
43 , "Saturn", "Uranus", "Neptune", "Pluto" };
44 floatdiameters[] = { 4800f, 12103.6f, 12756.3f, 6794f, 142984f
45 , 120536f, 51118f, 49532f, 2274f };
46 Map
47 for(inti = 0, n = names.length; i < n; i++)
48 map.put(names[i], newFloat(diameters[i]));
49 Iterator
50 while(it.hasNext()) {
51 String str = it.next();
52 System.out.println(str + ": " + map.get(str));
53 }
54 }
55
56 publicstaticvoidshowSynchronizedMap() {
57 TreeMap
58 Map
59 //Map之后的并发操作将不再需要synchronized关键字来进行同步了。
60 }
10. TreeMap:TreeMap和TreeSet之间的相似性和主要差异就像HashMap之于HashSet,见以下常用代码示例:
1 publicstaticvoidshowSubMapAndHeadMapAndTailMap() {
2 TreeMap
3 sortedMap.put("Adobe", "Mountain View, CA");
4 sortedMap.put("IBM", "White Plains, NY");
5 sortedMap.put("Learning Tree", "Los Angeles, CA");
6 sortedMap.put("Microsoft", "Redmond, WA");
7 sortedMap.put("Netscape", "Mountain View, CA");
8 sortedMap.put("O'Reilly", "Sebastopol, CA");
9 sortedMap.put("Sun", "Mountain View, CA");
10 System.out.println(sortedMap);
11 //firstKey and lastKey 是SortedMap中提供的方法,HashMap中没有。
12 String low = sortedMap.firstKey(), high = sortedMap.lastKey();
13 System.out.println(low);
14 System.out.println(high);
15 Iterator
16 inti = 0;
17 while(it.hasNext()) {
18 if(i == 3)
19 low = it.next();
20 if(i == 6)
21 high = it.next();
22 else
23 it.next();
24 i++;
25 }
26 System.out.println(low);
27 System.out.println(high);
28 //以下3个方法也是SortedMap中提供的方法,HashMap中没有。
29 System.out.println(sortedMap.subMap(low, high));
30 System.out.println(sortedMap.headMap(high));
31 System.out.println(sortedMap.tailMap(low));
32 }
11. LinkedHashSet和LinkedHashMap:这两个集合与HashSet和HashMap唯一的差异是LinkedHashSet和LinkedHashMap通过内部实现的双向链表保留了集合元素的插入顺序,见如下代码:
1 publicstaticvoidmain(String[] a) {
2 Map
3 map.put("1", "value1");
4 map.put("2", "value2");
5 map.put("3", "value3");
6 map.put("2", "value4");
7 for(Iterator