HashTable对整个Map加锁来保证线程安全,原始默认长度为11
public synchronized V remove(Object key) {
//确定当前key所在数据下标
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
//确定为某个链表
Entry<K,V> e = (Entry<K,V>)tab[index];
//初始prev为null,以后循环将e赋值给prev,e.next赋值给e
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) {
//当当前entry不为空时候,将e.next赋值给prev.next,将后续链表整体向前移动
prev.next = e.next;
} else {
//当链表表头为需删除的key时候,则将e.next赋值给表头,将后续链表整体向前移动
tab[index] = e.next;
}
count--;
V oldValue = e.value;
//将e.value赋值为null
e.value = null;
return oldValue;
}
}
return null;
}
put方法
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();
//确定下标,循环是否已有key,有的话替换,没有时候则调用addEntry方法,将值插入
int index = (hash & 0x7FFFFFFF) % tab.length;
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;
}
addEntry方法将值塞进table
private void addEntry(int hash, K key, V value, int index) {
//计数器
modCount++;
//当前table
Entry<?,?> tab[] = table;
//如果容量大于预制,则进行rehash扩容
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.
//则在相应的index下标下面创建新的Entry链表节点
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
rehash方法
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
// overflow-conscious code
//扩容为原容量的2被+1
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;
//将old的数据从新计算新的index,塞进新的table
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;
}
}
}
get方法
public synchronized V get(Object key) {
//计算下标,循环链表,如果key的hash和值都相等则返回对应的value,没有的时候则返回null
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;
}