Reputation: 1
As we know, null
is not allowed in Hashtable
.
But when I checked the source code of Hashtable
(jdk 1.8).
I only saw the check of value and couldn't find the key check.
Here is the source code below of the put
method:
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;
}
Upvotes: 0
Views: 111
Reputation: 97227
The key check is here:
int hash = key.hashCode();
This will throw a NullPointerException
if the key is null.
Upvotes: 5