HashMap
- 實現了Map接口
- 非線程同步,非線程安全
- 不允許重複鍵
- 鍵和值均允許爲null
HashMap<Interger,String> employeeHashmap=new HashMap<Integer,String>();
employeeHashmap.put(1,"Arpit");
employeeHashmap.put(2,null); // will work fine
HashTable
- 實現了Map接口
- 線程同步,線程安全
- 不允許重複鍵
- 鍵不允許爲null,值爲空時,運行時會拋出NPE
Hashtable<Interger,String> employeeHashmap=new Hashtable<Integer,String>();
employeeHashmap.put(1,"Arpit");
employeeHashmap.put(2,null); //not allowed and will throw NullPointer exception at run time
Hashtable vs HashMap
Parameter | HashTable | HashMap |
---|---|---|
線程安全 | 是 | 否 |
線程同步 | 是 | 否 |
性能 | 因爲線程安全,所以性能一般比HashMap慢 | 單線程環境下,性能比HashTable快,因爲單線程環境下推薦使用Hash Map |
空鍵 | 不允許 | 鍵和值都不允許爲空 |
Fail Fast | HashTable中的元素遍歷不支持FailFast | HashTable中的元素遍歷支持FailFast |
父類 | Dictionary | AbstractMap |
替代類 | 無 | 多線程環境下可以使用ConcurrentHashMap |
Fail-fast: 如果一個線程正在遍歷HashMap,同時另一個線程試圖修改(指刪除或者插入HashMap等試圖改變HashMap結構的行爲),就會拋出ConcurrentModification Exception
同步Hash Map
Map map=Collections.synchonizedMap(hashmap)