Hashmap和HashTable的区别:
1.HashMap线程不安全效率高,HashTable线程安全效率低
HashTable与hashmap虽然都实现了map接口,但hashTable是在hashmap的基础上加入了synchronized,所有线程进来都需要排队等候资源,所以hashtable的效率比hashmap低。
2.是否可以使用null来作为key和value
HashMap源码中put方法当key为空时,hash算法会返回0。 而hashtable当存入的value为null时会抛出空指针异常,当key为空时无法调用key.hashcode方法,因此也会抛出空指针异常
3.继承的类不同
HashMap继承了AbstractMap 类,HashTable继承了Dictionary类
4.容量扩容
HashMap的起始容量是16,Hashtable的起始容量为11,默认的负载因子都是0.75 当现有容量大于总容量*负载因子时,hashmap扩容规则是当前容量翻倍,hashtable则是翻倍加1
5.迭代器
HashMap的迭代器Iterator是fail-fast,而HashTable的Enumerator不是fail-fast. 当其他线程对HashMap的结构进行改变时,会报ConcurrentModificationException异常