Java集合: Map类

145 阅读1分钟

上图是Java集合的继承关系图,其中橘色的为class,我们重点看下这些class如何使用,继承细节部分本文不讨论。

Map

Map存储的是键值对,键不能重复。

HashMap

HashMap存储的顺序是无序的。

System.out.println("HashMap");
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("hello", "1");
hashMap.put("world", "2");
hashMap.put("hola", "3");

for(String i : hashMap.keySet()) {
    System.out.println(i + ": " + hashMap.get(i));
}
输出:
HashMap
world: 2
hello: 1
hola: 3

可以看到输出顺序和输入的顺序不一致。如何能够一致呢?需要用到下面的LinkedHashMap。

LinkedHashMap

LinkedHashMap存储的顺序是有序的,解决了HashMap无序的问题。

System.out.println("LinkedHashMap");
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
linkedHashMap.put("hello", "1");
linkedHashMap.put("world", "2");
linkedHashMap.put("hola", "3");

System.out.println("LinkedHashMap");
for(String i : linkedHashMap.keySet()) {
    System.out.println(i + ": " + linkedHashMap.get(i));
}
输出:
LinkedHashMap
hello: 1
world: 2
hola: 3

TreeMap

TreeMap实现了的排序,内部通过红黑树实现。

System.out.println("TreeMap");
TreeMap<String, String> treeMap = new TreeMap<String, String>();
treeMap.put("hello", "1");
treeMap.put("world", "2");
treeMap.put("hola", "3");
for(String i : treeMap.keySet()) {
    System.out.println(i + ": " + treeMap.get(i));
}
TreeMap
hello: 1
hola: 3
world: 2

可以看到内部实现了输出按照键的字典序从小大到排序。

HashTable

HashTable目前已经不推荐使用了,因此这里不做介绍了。

总结

  1. Map是键和值成对存储的数据结构;
  2. HashMap是Map的简单实现,不过存储的是无序的;
  3. LinkedHashMap存储的是有序的;
  4. TreeMap实现了按照排序;
  5. HashTable目前不推荐使用了。