Hashtable和Hashmap的区别

来源:互联网 发布:电子书网站 知乎 编辑:程序博客网 时间:2024/04/30 02:09
  关于Hashtable和Hashmap的区别,这个问题在面试中相信大家会经常碰到,这里做下备忘分享下吧。

 

一、继承关系区别:

 jdk1.6的源码中这两个类描述如下:

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

从上可以看出Hashtable和Hashmap都是实现了Map这个接口,不同的是Hashtable继承了Dictionary这个抽象类,HashMap继承了AbstractMap这个抽象类。

 

二、同步区别:

Hashtable类的主要方法都做了同步处理,但HashMap是非同步的。Hashmap的同步问题可通过Collections的一个静态方法得到解决:
Map Collections.synchronizedMap(Map m)
这个方法返回一个同步的Map,这个Map封装了底层的HashMap的所有方法,使得底层的HashMap即使是在多线程的环境中也是安全的。
或者使用java.util.concurrent包里的ConcurrentHashMap类。

 

三、NULL值区别:

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

HashTable不允许null值(key和value都不可以),HashMap允许null值(key和value都可以)。

 

四、Hash值获取区别:

还是通过源代码源代码,Hashtable是直接使用key对象的hash值。public synchronized V put(K key, V value) {       // Make sure the value is not null       if (value == null) {           throw new NullPointerException();       }        // Makes sure the key is not already in the hashtable.       Entry tab[] = table;       int hash = key.hashCode();//hashcode       int index = (hash & 0x7FFFFFFF) % tab.length;       //…}而HashMap则是利用key对象的hash值重新计算一个新的hash值。public V put(K key, V value) {        if (key == null)            return putForNullKey(value);        int hash = hash(key.hashCode());//hashcode        int i = indexFor(hash, table.length);        //…}


 

五、内部实现区别:

HashMap中内部数组的初始容量是16, 加载因子为0.75,而且数组容量增容后也要是2指数次幂:    /**     * The default initial capacity - MUST be a power of two.     */static final int DEFAULT_INITIAL_CAPACITY = 16;    /**     * The load factor used when none specified in constructor.     */    static final float DEFAULT_LOAD_FACTOR = 0.75f;HashTable中的内部数组的初始容量是11,加载因子也是0.75数组的增容方式为(oldCapacity * 2 + 1):public Hashtable() {       this(11, 0.75f); } protected void rehash() {       int oldCapacity = table.length;       Entry[] oldMap = table;        int newCapacity = oldCapacity * 2 + 1;       //…}Hashtable HashMap都使用了 Iterator。而由于历史原因,Hashtable还使用了Enumeration的方式 。


 

 

 

 

原创粉丝点击