4-2 Hashtable(2021-11-10)
1 Hashtable基本介绍
- 存放键值对。
- 键和值都不能是null,不然会抛出NullPointerException。
- 是线程安全的,HashMap线程不安全。
2 源码
2-1 无参构造函数
public Hashtable() {
this(11, 0.75f);
}
2-2 put
public synchronized V put(K key, V value) {
if (value == null) {
throw new NullPointerException();
}
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;
}