Step By Step(Java 集合篇) (七)

2014-11-24 03:19:39 · 作者: · 浏览: 12
}

38 }

39 }

40

41 class TestComparator {

42 public TestComparator(int id) {

43 _id = id;

44 }

45 public int getID() {

46 return _id;

47 }

48 public String toString() {

49 return Integer.toString(_id);

50 }

51 private int _id;

52 }

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

1 public static void showGetAndPut() {

2 HashMap hm = new HashMap();

3 hm.put("A", new Double(3.34));

4 hm.put("B", new Double(1.22));

5 hm.put("C", new Double(1.00));

6 hm.put("D", new Double(9.22));

7 hm.put("E", new Double(-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 double balance = hm.get("A");

15 //输出1003.34

16 hm.put("A", balance + 1000);

17 System.out.println(hm.get("A"));

18 }

19

20 public static void showContainsAndRemove() {

21 HashMap hashMap = new HashMap();

22 hashMap.put("1", "One");

23 hashMap.put("2", "Two");

24 hashMap.put("3", "Three");

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 st = hashMap.keySet();

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 public static void showIterator() {

42 String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter"

43 , "Saturn", "Uranus", "Neptune", "Pluto" };

44 float diameters[] = { 4800f, 12103.6f, 12756.3f, 6794f, 142984f

45 , 120536f, 51118f, 49532f, 2274f };

46 Map map = new HashMap();

47 for (int i = 0, n = names.length; i < n; i++)

48 map.put(names[i], new Float(diameters[i]));

49 Iterator it = map.keySet().iterator();

50 while (it.hasNext()) {

51 String str = it.next();

52 System.out.println(str + ": " + map.get(str));

53 }

54 }

55

56 public static void showSynchronizedMap() {

57 TreeMap treeMap = new TreeMap();

58 Map map = Collections.synchronizedMap(treeMap);

59 //Map之后的并发操作将不再需要synchronized关键字来进行同步了。

60 }

10. TreeMap:TreeMap和TreeSet之间的相似性和主要差异就像HashMap之于HashSet,见以下常用代码示例:

1 public static void showSubMapAndHeadMapAndTailMap() {

2 TreeMap sortedMap = new TreeMap();

3 sortedMap.put("Adobe", "Mountain View, CA");

4 sortedMap.put