HashTable是基于hash表实现的存储key-value数据的集合,它的所有方法都添加了同步锁,是线程安全的
特点
- 元素是无序的:元素存放位置是根据key值和数组长度运算的来的,无法确定顺序
- 元素的key不能重复,value可以重复
- 元素的key和value都不能为空:否则会抛出异常
- hash冲突:如果出现hash冲突,会在计算出的索引位形成链表存储
- 数组动态扩容:数组默认初始化容量为11,扩容比例因子是0.75。当数组元素个数达到容量的75%时会扩容,扩容为原始数组的两倍+1
- 链表不会转树:可能会出现链表过长的情况,如果数组没有达到扩容条件,链表的长度一直增加,会导致链表过长
- 线程安全:每个方法都加了同步锁,支持多线程访问
方法
构造方法
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {
//存储元素的数组
private transient Entry<?,?>[] table;
//实际元素个数
private transient int count;
//扩容阈值(临界值)
private int threshold;
//比例因子
private float loadFactor;
//修改次数(用于fail-fast判断)
private transient int modCount = 0;
private static final long serialVersionUID = 1421746759512286392L;
//创建一个Hashtable,手动设置初始化容量和比例因子
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);
}
//创建一个Hashtable,手动设置初始化容量
public Hashtable(int initialCapacity) {
this(initialCapacity, 0.75f);
}
//创建一个Hashtable,默认初始化容量和比例因子
public Hashtable() {
this(11, 0.75f);
}
//创建一个Hashtable,将传入集合元素复制到新数组
public Hashtable(Map<? extends K, ? extends V> t) {
this(Math.max(2*t.size(), 11), 0.75f);
putAll(t);
}
}
foreach
public synchronized void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
Entry<?, ?>[] tab = table;
//底层使用迭代器获取容器中的节点,调用传入函数操作
for (Entry<?, ?> entry : tab) {
while (entry != null) {
action.accept((K)entry.key, (V)entry.value);
entry = entry.next;
//如果循环时容器内节点被修改,直接抛出并发异常
if (expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
}
}
}
获取元素
//根据key获取value值
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已经存在,则直接更新value值
//key不存在,则添加到hashtbale中
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) {
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++;
modCount++;
}
扩容
//扩容:按照旧容量的2倍加1扩容成新数组的长度,重新计算临界值
//将旧数组中的数据复制到新数组
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;
}
}
}
删除
//遍历查找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)) {
//不是在链表头部:将查找到的节点从链中解除绑定,将e的前一个节点指向e的后一个节点
if (prev != null) {
prev.next = e.next;
}
//如果是链表头部或只有索引位有值,直接将e.next放入索引位
else {
tab[index] = e.next;
}
modCount++;
count--;
V oldValue = e.value;
e.value = null;
return oldValue;
}
}
return null;
}