面試題中常有HashMap和Hashtable的異同比較題,今天閑著無事,做了一點小比較,實驗結(jié)果如下:
|
HashMap |
Hashtable |
允許空鍵 |
允許 |
不允許 |
允許空值 |
允許 |
不允許 |
以空鍵取值 |
能取到值 |
|
取空值 |
能取得 |
|
插值速度 |
稍高 |
稍低 |
取值速度 |
高 |
低 |
遍歷速度 |
兩者差不多 |
兩者差不多
|
測試代碼如下:
package com.sitinspring;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> hashMap = new HashMap<String, String>();
Map<String, String> hashTable = new Hashtable<String, String>();
// 測試一:往兩者中放空鍵,hashMap允許,hashTable不允許,第二句會拋出空指針異常
hashMap.put(null, "value");
hashTable.put(null, "value");
// 測試二:往兩者中放空值,hashMap允許,hashTable不允許,第二句也會拋出空指針異常
hashMap.put("key", null);
hashTable.put("key", null);
// 測試三:以空鍵取hashMap中的值,結(jié)果能夠取到"value"
String value = hashMap.get(null);
System.out.println("取出的值等于" + value);
// 測試四:以鍵"key"取hashMap中的值,結(jié)果能夠取到null
String value2 = hashMap.get("key");
System.out.println("取出的值等于" + value2);
// 測試五:插值速度比較,兩者差別不大
int max=100000;
TimeTest tableTimeTest=new TimeTest();
setValuesToMap(hashTable,max);
tableTimeTest.end("往hashTable插"+max+"值耗時");
hashMap.clear();// 清楚掉原來加入的值
TimeTest mapTimeTest=new TimeTest();
setValuesToMap(hashMap,max);
mapTimeTest.end("往hashMap插"+max+"個值耗時");
// 測試六:取值速度比較,hashTable速度平均約為hashMap的四分之一到七分之一
TimeTest tableTimeTest2=new TimeTest();
getValuesFromMap(hashTable,max);
tableTimeTest2.end("從hashTable取"+max+"值耗時");
TimeTest mapTimeTest2=new TimeTest();
getValuesFromMap(hashMap,max);
mapTimeTest2.end("往hashMap取"+max+"個值耗時");
// 測試七:遍歷速度比較,hashTable速度和hashMap的差不多
TimeTest tableTimeTest3=new TimeTest();
traversalMap(hashTable);
tableTimeTest3.end("遍歷hashTable耗時");
TimeTest mapTimeTest3=new TimeTest();
traversalMap(hashMap);
mapTimeTest3.end("遍歷hashMap耗時");
}
private static void setValuesToMap(Map<String,String> map,int max){
for(int i=0;i<max;i++){
String str=String.valueOf(i);
map.put(str, str);
}
}
private static void getValuesFromMap(Map<String,String> map,int max){
for(int i=0;i<max;i++){
String str=map.get(i);
}
}
private static void traversalMap(Map<String,String> map){
Iterator it=map.keySet().iterator();
while(it.hasNext()){
String key=(String)it.next();
String value=map.get(key);
}
}
}
package com.sitinspring;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TimeTest {
private Calendar startTime;
public TimeTest() {
startTime = new GregorianCalendar();
}
public void end(String functionName) {
Calendar endTime = new GregorianCalendar();
int miniteSpan = endTime.get(Calendar.MINUTE)
- startTime.get(Calendar.MINUTE);
int secondSpan = endTime.get(Calendar.SECOND)
- startTime.get(Calendar.SECOND);
int msecondSpan = endTime.get(Calendar.MILLISECOND)
- startTime.get(Calendar.MILLISECOND);
System.out.println(functionName + " " + String.valueOf(miniteSpan)
+ " 分 " + String.valueOf(secondSpan) + " 秒 "
+ String.valueOf(msecondSpan) + " 毫秒 ");
}
}
代碼下載:
http://m.tkk7.com/Files/sitinspring/HashMapHashtable20071215212107.rar