總結一下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