这个从源码中能够直接看出来,HashMap 继承自 AbstractMap,而 Hashtabl 继承自 Dictionary。html
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable
Hashtable 在不少方法定义时都会加上 synchronized
关键字,说明 Hashtabl 是线程安全的,而 HashMap 并不能保证线程安全。java
public synchronized int size(); public synchronized boolean isEmpty(); public synchronized boolean contains(Object o); public synchronized V get(Object key); public synchronized V put(K key, V value); ...
在 Hashtable 添加元素源码中,咱们能够发现,若是添加元素的 value 为 null 时,会抛出 NullPointerException。在程序内部,有这样一行代码 int hash = key.hashCode
,若是添加的 key 为 null 时,此时也会抛出空指针异常,所以,在 Hashtable 中,是不容许 key 和 value 为 null 的。算法
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(); int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> entry = (Entry<K,V>)tab[index]; for(; entry != null ; entry = entry.next) { if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value; return old; } } addEntry(hash, key, value, index); return null; }
而在 HashMap 的 put 方法中,调用了 putVal
方法(1.8 版本中),该方法须要有一个 int 类型的 hash
值,这个值是利用内部的 hash
方法产生的。从下面的源代码能够看出,当 key 为 null 时,返回的 hash 值为 0,说明在 HashMap 中是容许 key=null 的状况存在的。数组
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict){ } static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
从 HashMap 的 API 能够看出,它只包含 containsKey 和 containsValue 方法。而 Hashtable 还包含了 contains 方法。安全
HashMap 中把 contains 方法去掉的缘由主要它容易引发混淆,不如 containsKey 和 containsValue 表达的准确。this
而 Hashtable 中 contains 方法也是调用 containsKey 方法来实现的。线程
public boolean contains(Object o) { return containsKey(o); }
Hashtable 初始容量为 11,默认的负载因子为 0,.75。HashMap 定义了两个常量在对容器进行初始化会用到,能够看到其初始容量为 16,默认的负载因子也是为 0.75.指针
//---------------------Hashtable----------------------------- public Hashtable() { this(11, 0.75f); } public Hashtable(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal Load: "+loadFactor); if (initialCapacity==0) initialCapacity = 1; this.loadFactor = loadFactor; // 这里对桶进行初始化 table = new Entry<?,?>[initialCapacity]; threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1); } //---------------------HashMap----------------------------- /** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f;
Hashtable 扩容时调用 rehash
方法,增长容器容量的代码在下面。从中能够看出,最终的容量是 newCapacity
,若是该变量在没有大于 MAX_ARRAY_SIZE
(静态变量,内部定义为 Integer.MAX_VALUE - 8) 以前,都是按照 oldCapacity*2 + 1 的速度增长的。code
int newCapacity = (oldCapacity << 1) + 1; if (newCapacity - MAX_ARRAY_SIZE > 0) { if (oldCapacity == MAX_ARRAY_SIZE) // Keep running with MAX_ARRAY_SIZE buckets return; newCapacity = MAX_ARRAY_SIZE; } Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
在 HashMap 中,扩容主要是经过 resize
方法实现的,其扩容的代码是这样的 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
,可见是跟 newCap 变量有关,在正常状况下,newCapa 是按照 oldCap<<1
的速度,即每次长度变为原来的两倍增加的。htm
if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); }
本段话摘自 http://www.cnblogs.com/alexlo/archive/2013/03/14/2959233.html
HashMap 的迭代器(Iterator) 是 fail-fast 迭代器,而 Hashtable 的 enumerator 迭代器不是 fail-fast 的。因此当有其它线程改变了 HashMap 的结构(增长或者移除元素),将会抛出 ConcurrentModificationException,但迭代器自己的 remove() 方法移除元素则不会抛出 ConcurrentModificationException 异常。但这并非一个必定发生的行为,要看 JVM 。这条一样也是 Enumeration 和 Iterator 的区别。关于 fail-fast 机制能够查看这篇文章。
一下下这段分析摘自:http://www.javashuo.com/article/p-sxehvotn-dc.html hash 算法是将元素定位到相对应桶的位置上,在 Hashtable 中,是这样实现 hash 算法的。由于 Hashtable 中,其桶扩容以后长度为奇数,这种方式的哈希取模会更加均匀(这点仍是不清楚为何)。
int hash = key.hashCode(); // hash 不能超过 Integer.MAX_VALUE,因此要取其最小的 32 个 bit int index = (hash & 0x7FFFFFFF) % tab.length;
在 JDK 1.8 版本中,HashMap 的 hash 方法以下。
static final int hash(Object key){ int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } final V putValu(int hash,K key,V value,boolean onlyIfAbsent,boolean evict){ ... if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); ... }
异或
运算,返回结果。(n-1)&hash
获取该对象的键在 hashmap 中的位置。(其中 hash 就是经过 hash 方法得到的值),n 表示 hash 桶数组的长度,而且该长度为 2 的 n 次方。一般声明 map 集合时不会指定大小,或者初始化的时候就建立一个容量很大的map 对象,因此这个经过容量大小与 key 值进行 hash 的算法在开始的时候只会对低位进行计算,虽然容量的 2 进制高位一开始都是 0,可是 key 的 2 进制高位一般是有值的,所以先在 hash 方法中将 key 的 hashCode 右移 16 位在与自身异或,使得高位也能够参与hash,更大程度上减小了碰撞率。