Map 接口中,key 和 value 都可以为 null。
HashTable 实现中,key 和 value 都不允许为 null。
我们看一下它添加元素的方法:
public synchronized V put(K key, V value) {
if (value == null) { // value 不能为 null
throw new NullPointerException();
}
Entry<?,?> tab[] = table;
int hash = key.hashCode(); // key 不能为 null
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) { // 添加新 Entry 的复杂度为 O(n)
if ((entry.hash == hash) && entry.key.equals(key)) { // 如果 hash 值已经存在,则用新值覆盖旧值
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) {
modCount++;
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;
}
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e); // 如果 hash 冲突,则插到队列头。
count++;
}
private transient Entry<?,?>[] table;
从代码中我们可以看出以下几点:
1. key 和 value 都不能为 null。
2. 添加新 Entry 的复杂度为 O(n)。
3. 如果 key 已经存在,则直接覆盖。
4. 如果 hash 冲突,就插到队列头部。不插到尾部,因为插到头部效率更高。
我们可以看一下 Entry 类:
private static class Entry<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Entry<K,V> next;protected Entry(int hash, K key, V value, Entry<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
...
Entry 本质上就是一个单向链表的节点。
另外,HashTable 是同步的,除了构造函数意外,它的每个共有方法都是同步的:
1. 被 synchronized 修饰:
1.1. 直接修饰:
public synchronized V put(K key, V value)
1.2 间接修饰 :
public boolean containsValue(Object value) {
return contains(value);
}
public synchronized boolean contains(Object value)
2. 返回 synchronized 版本的集合:
public Set<K> keySet() {
if (keySet == null)
keySet = Collections.synchronizedSet(new KeySet(), this);
return keySet;
}
总结:
1. HashTable 基于数组 + 链表实现。插入元素的复杂度为 O(n)。
2. HashTable 的 key 和 value 都不允许为 null。
3. HashTable 是同步的。
参考链接: