Hashtable的数据结构其实就是一个hash表(数组),然后hash表中存的是entry,entry是key,value的映射。
结构如图:
下面是Hashtable的源码:
1、添加数据的源码:
// 1、首先这个方法是上锁了的,所以Hashtable是线程安全的,但是进行组合调用就不是线程安全的了
public synchronized V put(K key, V value) {
// 2、判断添加的value是不是为空,为空则抛出异常,说明:Hashtable是不允许添加null
if (value == null) {
throw new NullPointerException();
}
// 3、判断该key是否已经存在,如果存在就覆盖原来的值
Entry<?,?> tab[] = table;
int hash = key.hashCode();
// 计算index的方式
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;
}
}
// 4、如果key不存在就添加数据
addEntry(hash, key, value, index);
return null;
}
private void addEntry(int hash, K key, V value, int index) {
modCount++;
Entry<?,?> tab[] = table;
// 1、判断容量是否超过了阈值,如果超过了阈值就需要rehash,rehash就是对数组扩容,然后对所有数据从新计算hash,该过程非常消耗资源
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// 然后将新增的数据创建一个entry,将entry放入数组中
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}