Map接口定义了以key,value形式存数据,通过key映射将某个value存储到某个地址下的方式来实现。
Map下实现的接口有hashMap,hashTable,LinkedHashMap,TreeMap等一系列的实现类
一个丑丑的uml图献上
1.HashMap
我们最常用的Map实现,底层采用数组+单链表+红黑树实现的,存的数据取出来是无序的(所以对应就会出现有序的实现LinkedHashMap)!但是hashMap的查找效率是很高的哦!
public static void main(String[] args) {
Map<String,String> map = new HashMap(16);
map.put("2", "xxh");
map.put("1", "df");
map.put("6", "er");
map.put("68", "er");
map.put("80", "er");
for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
Object key = it.next();
System.out.println(key + "=" + map.get(key));
}
}
2.TreeMap
底层红黑树实现的,存的数据取出来是无序的,因为会根据它的key自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序。
public static void main(String[] args) {
Map<String,String> map = new TreeMap();
map.put("2", "xxh");
map.put("1", "df");
map.put("6", "er");
map.put("68", "er");
map.put("80", "er");
for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
Object key = it.next();
System.out.println(key + "=" + map.get(key));
}
}
看吧,按照key自动的排为了升序。
自定义排序实现倒叙试试
public static void main(String[] args) {
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
};
Map<Integer, Integer> map = new TreeMap(comparator);
map.put(2, 3);
map.put(1, 5);
map.put(6, 2);
map.put(68, 6);
map.put(80, 9);
for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
Object key = it.next();
System.out.println(key + "=" + map.get(key));
}
}
如果不需要排序的话尽量使用HashMap,因为TreeMap采用的红黑树,插入,删除也好需要维持平衡,查询的话因为HashMap是采用映射查询,TreeMap是树所以会依次遍历查找,所以性能还是HashMap好
3.LinkedHashMap
LinkedHashMap底层采用的是链表实现,插入数据与存储数据是顺序是一致的。
public static void main(String[] args) {
Map<Integer, Integer> map = new LinkedHashMap();
map.put(2, 3);
map.put(1, 5);
map.put(6, 2);
map.put(68, 6);
map.put(80, 9);
for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
Object key = it.next();
System.out.println(key + "=" + map.get(key));
}
}
4.HashTable
线程安全的HashMap,直接把synchronized加入到方法里了,所以性能不高,一般不建议使用HashTable,线程安全建议使用ConcurrentHashMap,ConcurrentHashMap采用CAS+synchronized方式实现的,所以性能会很高