Map源码解析之HashMap
Map源码解析之HashMap红黑树
Map源码解析之HashMap补充:集合、迭代器、compute、merge、replace
Map源码解析之LinkedHashMap
Map源码解析之TreeMap
之前文章分析的HashMap、LinkedHashMap、TreeMap虽然有各自不同的特性,但是它们都是线程不安全的,这一篇文章中,我们将解析线程安全的类HashTable。
HashMap通过synchronized关键字实现线程安全,对HashTable的操作均通过synchronized方法实现。HashTable的key值和value值都不能为null。HashTable的数据结构和jdk1.7及之前的HashMap一样,为数组+链表。
一、主要的成员变量
由链表的头结点组成的数组:private transient Entry<?,?>[] table;
节点数量:private transient int count;
扩容阈值:private int threshold;
负载因子,默认0.75:private float loadFactor;
修改次数,增加或删除节点时会增加:private transient int modCount = 0;
二、主要的成员类
1. HashTable.Entry
HashTable的节点类,有hash值、key值、value值和指向下一个节点的next组成。
private static class Entry<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Entry<K,V> next;
//省略方法
}
三、构造方法
1. public Hashtable()
以11和0.75作为参数调用public Hashtable(int initialCapacity, float loadFactor)实现。
public Hashtable() {
this(11, 0.75f);
}
2. public Hashtable(int initialCapacity)
以initialCapacity和0.75作为参数调用public Hashtable(int initialCapacity, float loadFactor)实现。
public Hashtable(int initialCapacity) {
this(initialCapacity, 0.75f);
}
3. public Hashtable(int initialCapacity, float loadFactor)
首先对参数进行校验,然后设置负载因子loadFactor 和扩容阈值threshold ,初始化数组。
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);
}
4. public Hashtable(Map<? extends K, ? extends V> t)
以2*t.size()(最小11)和0.75作为参数调用public Hashtable(int initialCapacity, float loadFactor)实现,然后通过HashTable#putAll将元素加入。
public Hashtable(Map<? extends K, ? extends V> t) {
this(Math.max(2*t.size(), 11), 0.75f);
putAll(t);
}
四、 扩容方法
rehash为HashTable的扩容方法
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
// overflow-conscious 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];
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;
}
}
}
可以看到其除了没有红黑树以外和HashMap还有以下不同:
(1) 节点的hash值
HashTable的节点的hash值为key值的hashcode的后31位 e.hash & 0x7FFFFFFF
HashMap的节点的hash值为key值的hashcode的高16位与低16位的异或结果
(2)数组的位置
HashTable的节点通过取余的方式确定其在数组的位置 (hash & 0x7FFFFFFF) % tab.length
HashMap的节点通过按位与的方式实现和取余一样的结果
(3)扩容时节点在数组的新位置
HashTable的节点依旧是取余的方式确定其在数组的新位置 (e.hash & 0x7FFFFFFF) % newCapacity
HashMap的节点通过hash值与旧容量与运算的结果是否为0确定其在数组的新位置
(3)扩容时链表的移植
HashTable通过头插法实现链表移植
HashMap通过尾插法实现链表移植
五、put方法
1. public synchronized V put(K key, V value)
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;
}
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++;
}
整体逻辑与HashMap一致,先根据key值查找节点,找到节点则覆盖并返回,没有找到则插入新节点。插入节点后判断是否需要进行扩容,需要则进行相关扩容操作。
六、get方法
1. public synchronized V get(Object key)
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
根据key值的hash值确定数组位置后遍历链表
七、remove方法
1. public synchronized V remove(Object key)
public synchronized V remove(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>)tab[index];
for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count--;
V oldValue = e.value;
e.value = null;
return oldValue;
}
}
return null;
}
根据key值找到节点后删除并返回
2. public synchronized boolean remove(Object key, Object value)
public synchronized boolean remove(Object key, Object value) {
Objects.requireNonNull(value);
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>)tab[index];
for (Entry<K,V> prev = null; e != null; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key) && e.value.equals(value)) {
modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count--;
e.value = null;
return true;
}
}
return false;
}
根据key值找到节点,判断节点的value值和value参数是否匹配,如果配置则删除并返回true