Hashtable源码
添加一个数据
1.创建一个11大小的数组Entry
private transient Entry<?,?>[] table;
2.计算key的hashcode(),计算数据添加到索引的位置
// Entry table赋值给新的Entry tab数组,此时都是11容量
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
3.tab计算索引的位置赋值到entry数组,这里主要如果计算出索引位置有值,但是值不同或者不同对象值不同,就添加到链表后面
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;
}
}
4.调用添加addEntry
addEntry(hash, key, value, index);
5.进去addEntry方法,超过临界值实现扩容
//table空数组赋值给tab
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;
}
6.真正的实现赋数组值
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);