我们知道,null不允许进入Hashtable.但是当我检查Hashtable(jdk 1.8)的源代码时.我只看到了价值检查,无法找到钥匙检查.以下是该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();
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;
}
Run Code Online (Sandbox Code Playgroud)
关键检查在这里:
int hash = key.hashCode();
Run Code Online (Sandbox Code Playgroud)
NullPointerException如果键为null,则抛出一个.
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |