Java HashMap 和 Hashtable 区别

  1. 继承不同。

    public class Hashtable extends Dictionary implements Map

    public class HashMap extends AbstractMap implements Map

  2. Hashtable 中的方法是同步的,而 HashMap 中的方法在缺省情况下是非同步的。在多线程并发的环境下,可以直接使用 Hashtable,但是要使用 HashMap 的话则要自己增加同步处理。Hashtable 的方法是线程安全的,而 HashMap 不是线程安全的。

  3. Hashtable中,key 和 value 都不允许出现 null 值。

    HashMap 中,null 可以作为键,这样的键只有一个;可以有一个或多个键所对应的值为 null。当 get() 方法返回 null 值时,既可以表示 HashMap 中没有该键,也可以表示该键所对应的值为 null。因此,在 HashMap 中不能由 get() 方法来判断 HashMap 中是否存在某个键, 而应该用 containsKey() 方法来判断。

  4. 遍历方式的内部实现上不同。

    Hashtable、HashMap 都使用了 Iterator。而由于历史原因,Hashtable 还使用了 Enumeration 的方式。

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

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

  7. HashMap 没有 contains 方法,只有 containsValue 和 containsKey。Hashtable 三者都有。

发布了42 篇原创文章 · 获赞 86 · 访问量 7028

猜你喜欢

转载自blog.csdn.net/siriusol/article/details/105044815