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)