面试系列-HashTable与HashMap的区别

来源:互联网 发布:mac升级中解压软件损坏 编辑:程序博客网 时间:2024/05/16 13:59

结论现行

Hashtable HashMap 同步 非同步 不允许null 允许null 线程安全 线程不安全 速度慢 速度快

同步

源码中是这样对HashTable进行解释的:

This class implements a hash table, which maps keys to values. Anynon-<code>null</code> object can be used as a key or as a value. <p>

任何非null的对象都可用作键或值.

As of the Java 2 platform v1.2, this class has been retrofitted to implement Map, so that it becomes a part of Java's collection framework. Unlike the new collection implementations, Hashtable is synchronized.

后期实现了Map接口才被纳入集合体系,并且是同步的

再来看看HashMap:

Hash table based implementation of the <tt>Map</tt> interface.  Thisimplementation provides all of the optional map operations, and permits<tt>null</tt> values and the <tt>null</tt> key.  (The <tt>HashMap</tt>class is roughly equivalent to <tt>Hashtable</tt>, except that it isunsynchronized and permits nulls.)  This class makes no guarantees as tothe order of the map; in particular, it does not guarantee that the orderwill remain constant over time.

HashMap基本上等价于Hashtable,只不过他是非同步的并且允许null键null值.

速度

Hashtable是同步的在多线程情况下就能保证线程安全,这同时也意味着在单线程情况下不如HashMap速度快

感想

本文极短,但用来应对简单的面试已经够了.贴上了大量原文官方注释是想表示,有问题先找第一手资料,这样可以少走很多弯路.