以jdk1.8为例:
- HashMap 是线程不安全的,HashTable 是线程安全的,大部分的方法都是用sychronized修饰加锁了。
- HashMap 的底层实现是 Node数组+链表+红黑树 的结构,Node数组长度小于64的时候,链表不会转化为红黑树,只会对数组进行扩容。HashTable的底层实现是Map.Entry的数组。
- HashMap 的默认容量是16,每次扩容容量扩充一倍。HashTable的默认容量是11,每次扩充容量扩容为2n+1。
- HashMap 的key和value的值都可以为null,key的值只能有一个为null,value的值可以有多个为null。HashTable的key和value不能为null,为null会报NullPointerException。
- HashMap计算hash值时使用了高位和低位异或计算的混合扰动处理减少hash冲突,HashTable没有这种处理,直接取的key的hashCode值。
HashMap相关代码:
// 默认容量是16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 最大容量,如果隐式指定了一个更高的值,则使用该值通过任何一个带参数的构造函数
// 必须是2的幂
static final int MAXIMUM_CAPACITY = 1 << 30;
// 负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转化为树的阈值(必须大于2,且最少是8)
static final int TREEIFY_THRESHOLD = 8;
// 树转化为链表的阈值(必须比TREEIFY_THRESHOLD小,最大为6)
static final int UNTREEIFY_THRESHOLD = 6;
// 链表转化为树的最小数组容量(Hash冲突导致同一个数组的节点下链表长度超过阈值且Node数组长度不足64时,优先对数组进行扩容。这个阈值应该至少是4倍的TREEIFY_THRESHOLD)
static final int MIN_TREEIFY_CAPACITY = 64;
// 计算hash桶的索引
static final int hash(Object key) {
int h;
// 若key为null,则在索引为0的hash桶中保存元素
// 否则,取当前key的hashCode的高位与低位16位的异或值作为hash桶索引
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; // 第一次存储元素,调用resize()扩容
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null); // 没有发生hash冲突,构建Node对象,存储元素
else { // 发生hash冲突
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p; // key在map中已存在,直接覆盖value
else if (p instanceof TreeNode) // 当前节点已经是树节点(已经完成了从链表到红黑树的转变)
// 在树中插入代表新内容的节点
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash); // 链表转化为红黑树
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize(); // 元素超过阈值,扩容
afterNodeInsertion(evict);
return null;
}
HashTable相关代码:
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException(); // HashTable的value不为null
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode(); // HashTable的key不为null
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;
}
private void addEntry(int hash, K key, V value, int index) {
modCount++;
Entry<?,?> tab[] = table;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
// overflow-conscious code
int newCapacity = (oldCapacity << 1) + 1; //扩容2n+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];
modCount++;
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = (Entry<K,V>)newMap[index];
newMap[index] = e;
}
}
}