在阅读JDK源代码时,我发现作者通常会检查参数是否为null,然后手动抛出新的NullPointerException().他们为什么这样做?我认为没有必要这样做,因为它会在调用任何方法时抛出新的NullPointerException().(这里是HashMap的一些源代码,例如:)
public V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (remappingFunction == null)
throw new NullPointerException();
Node<K,V> e; V oldValue;
int hash = hash(key);
if ((e = getNode(hash, key)) != null &&
(oldValue = e.value) != null) {
V v = remappingFunction.apply(key, oldValue);
if (v != null) {
e.value = v;
afterNodeAccess(e);
return v;
}
else
removeNode(hash, key, null, false, true);
}
return null;
}
Run Code Online (Sandbox Code Playgroud)