The difference between HashTable and HashMap (very important)

The difference between HashTable and HashMap

First, the inherited parent class is different.
Hashtable inherits from the Dictionary class, and HashMap inherits from the AbstractMap class. But both implement the Map interface.

Copy the code code as follows:

public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, Serializable
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable


**第二,线程安全性不同。**
Hashtable 中的方法是Synchronize的,而HashMap中的方法在缺省情况下是非Synchronize的。在多线程并发的环境下,可以直接使用Hashtable,不需要自己为它的方法实现同步,但使用HashMap时就必须要自己增加同步处理。
第三,是否提供contains方法
HashMap把Hashtable的contains方法去掉了,改成containsValue和containsKey,因为contains方法容易让人引起误解。

Hashtable则保留了contains,containsValue和containsKey三个方法,其中contains和containsValue功能相同。

第四,key和value是否允许null值。
其中key和value都是对象,并且不能包含重复key,但可以包含重复的value。
**Hashtable中,key和value都不允许出现null值**。
HashMap中,null可以作为键,这样的键只有一个;可以有一个或多个键所对应的值为null。当get()方法返回null值时,可能是 HashMap中没有该键,也可能使该键所对应的值为null。因此,在HashMap中不能由get()方法来判断HashMap中是否存在某个键, 而应该用containsKey()方法来判断。

第五,两个遍历方式的内部实现上不同。
Hashtable、HashMap都使用了 Iterator。而由于历史原因,Hashtable还使用了Enumeration的方式 。

第六,hash值不同。
哈希值的使用不同,HashTable直接使用对象的hashCode。而HashMap重新计算hash值。

第七,内部实现使用的数组初始化和扩容方式不同。
Hashtable和HashMap它们两个内部实现方式的数组的初始大小和扩容的方式。**********************HashTable中hash数组默认大小是11,增加的方式是 old*2+1。
HashMap中hash数组的默认大小是16,而且一定是2的指数。**

Guess you like

Origin blog.51cto.com/14232658/2486452