总结一下Map的三个实现类HashMap、LinkedHashMap、TreeMap的消耗时间,例子通过用String为键,索引到Integer值和倒过来建立Map,不难发现如下规律:
Types | HashMap | LinkedHashMap | TreeMap |
---|---|---|---|
Map<Integer,String> | 112ms,数字递增排序 | 2ms,数字递增排序 | 1ms,数字递增排序 |
Map<String,Integer> | 2ms,插入顺序 | <1ms,插入顺序 | <1ms,字母表递增排序 |
TODO: 源码解析
不多说,直接上代码:
import java.util.*;
public class MapDeatil {
public static void testMap1(){
Map<Integer, String> hashMap=new HashMap<>();
hashMap.put(1,"Smith");
hashMap.put(6,"Ant");
hashMap.put(3,"AHS");
hashMap.put(8,"JKA");
hashMap.put(5,"BVmm");
long preTime=System.currentTimeMillis();
hashMap.forEach((num,name)->System.out.println(num+","+name));
long postTime=System.currentTimeMillis();
System.out.println("hashset时间:"+(postTime-preTime));
Map<Integer, String> linkedHashMap=new LinkedHashMap<>(hashMap);
preTime=System.currentTimeMillis();
linkedHashMap.forEach((num,name)->System.out.println(num+","+name));
postTime=System.currentTimeMillis();
System.out.println("hashset时间:"+(postTime-preTime));
Map<Integer,String> treeMap=new TreeMap<Integer, String>(hashMap);
preTime=System.currentTimeMillis();
treeMap.forEach((num,name)->System.out.println(num+","+name));
postTime=System.currentTimeMillis();
System.out.println("hashset时间:"+(postTime-preTime));
}
public static void testMap2(){
Map<String,Integer> hashMap=new HashMap<>();
hashMap.put("Smith",30);
hashMap.put("Ant",20);
hashMap.put("AHS",21);
hashMap.put("JKA",25);
hashMap.put("BVmm",33);
long preTime=System.currentTimeMillis();
hashMap.forEach((num,name)->System.out.println(num+","+name));
long postTime=System.currentTimeMillis();
System.out.println("hashset时间:"+(postTime-preTime));
Map<String, Integer> linkedHashMap=new LinkedHashMap<>(hashMap);
preTime=System.currentTimeMillis();
linkedHashMap.forEach((num,name)->System.out.println(num+","+name));
postTime=System.currentTimeMillis();
System.out.println("linkedhashset时间:"+(postTime-preTime));
Map<String, Integer> treeMap=new TreeMap<>(hashMap);
preTime=System.currentTimeMillis();
treeMap.forEach((num,name)->System.out.println(num+","+name));
postTime=System.currentTimeMillis();
System.out.println("treeset时间:"+(postTime-preTime));
}
public static void main(String[] args) {
testMap1();
testMap2();//如果以String为key查询Integer,比反过来更快
}
}
输出如下:
1,Smith
3,AHS
5,BVmm
6,Ant
8,JKA
hashset时间:112
1,Smith
3,AHS
5,BVmm
6,Ant
8,JKA
hashset时间:2
1,Smith
3,AHS
5,BVmm
6,Ant
8,JKA
hashset时间:1
JKA,25
Ant,20
Smith,30
BVmm,33
AHS,21
hashset时间:2
JKA,25
Ant,20
Smith,30
BVmm,33
AHS,21
linkedhashset时间:0
AHS,21
Ant,20
BVmm,33
JKA,25
Smith,30
treeset时间:0