hashMap和hashTable的区别
一、HashMap的简单介绍
1、HashMap是基于hash表的map接口实现,每一个元素都以key-value 存储,hashMap的默认大小为16,当容量不足时,会自动增加。
2、HashMap是非synchronized 线程不安全的,只是用于单线程环境下。
3、HashMap的简单使用及原理:
1) 使用map.put(key, value)存储对象到HashMap中
2) 使用map.get(key)从HashMap中获取对象。
3) 当我们给put()方法传递键和值时,我们先对键调用hashCode()方法,计算并返回的hashCode是用于找到Map数组的bucket位置来储存Entry数组对象HashMap是在bucket中储存键对象和值对象,作为一个存储点。
4、HashMap 实现了Serializable接口,支持序列化,实现了Cloneable接口,可以被克隆clone
5、HashMap中key和value 都允许为null
// 声明hashMap变量
HashMap<Object,Object> aMap=new HashMap<Object,Object>();
aMap.put(null,null);
// 输出 为 null
System.out.println(aMap.get(null));
二、HashTable的简单介绍
1、HashTable 也是实现了Map接口
2、HashTable 是 synchronized 线程安全的,效率比较低
3、hashTable 的key和value不能为空
4、HashTable 实现了Serializable接口,支持序列化,实现了Cloneable接口,可以被克隆clone
三、区别
1、父类不同
Hashtable继承自Dictionary类,而HashMap继承自AbstractMap类,但是两者都实现了MAP接口
2、线程安全性不同
HashTable中的方法是 Synchronize的,而HashMap中的方法在是非Synchronize的,在多线程情况下,可以直接用HashTable不需要在去实现同步,但是在使用HashMap的时候就必须自己实现同步
3、key和value是否允许null值
HashMap允许key和value为null,HashTable 不允许key和value为null
4、contains方法
HashMap中有containsValue和containsKey方法
HashTable 中有 contains containsValue ,containsKey三个方法
5、初始化容量和扩容方式不同
hashMap的初始容量大小默认为16,而HashTable是11, HashMap扩容时,将容量变为原来的2倍(2n)。Hashtable扩容时,将容量变为原来的2倍加1(2N+1),
参考博客 :https://www.cnblogs.com/williamjie/p/9099141.html