Map與List查詢效能比較
@Test
public void mapTest(){
/*
* 比較順序查詢和雜湊查詢的效能
*/
//建立線性表集合
List<String> list=
new ArrayList<String>();
//建立散列表集合
Map<String, Integer> map=
new HashMap<String, Integer>();
//向集合中同時新增資料
for(int i=0; i<500000; i++){
String key="Tom"+i;
list.add(key);
//將key,value成對的加入到map
map.put(key, i);//Tom0, 0
}
//被查詢的 key
String key = "Tom499999";
//線性表中順序查詢:
long t1=System.nanoTime();
int i=list.indexOf(key);
long t2=System.nanoTime();
System.out.println(i+","+(t2-t1)); //499999,11245379
//散列表中的雜湊查詢:
t1=System.nanoTime();
int n = map.get(key);
t2=System.nanoTime();
System.out.println(n+","+(t2-t1)); //499999,15317
}
//散列表效能更高
1,查詢
根據key的雜湊值(hashcode())對映到雜湊陣列的下標再根據key的equals方法逐一比較key,最後找到value。
2,新增/替換:
根據key的雜湊值(hashCode())對映到雜湊陣列的下標,再根據key的equals方法逐一比較key,最後找到插入(替換)位置,插入(替換)key-value資料。
記住:無論查詢還是新增都是先用key的hashCode再使用key的equals方法
注意:使用散列表時候,作為key的物件,必須重寫equals和hashCode。