Reputation: 1090
containsValue()
is implemented in AbstractMap
class as below:
public boolean containsValue(Object value) {
Iterator<Entry<K,V>> i = entrySet().iterator();
if (value==null) {
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (e.getValue()==null)
return true;
}
} else {
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (value.equals(e.getValue()))
return true;
}
}
return false;
}
What if the implementation had been as below:
public boolean containsValue(Object value) {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (e.getValue().equals(value))
return true;
}
return false;
}
Is there any performance improvement by implementing a null specific checking in the original method?
Upvotes: 1
Views: 379
Reputation: 393771
In your suggested implementation, e.getValue().equals(value)
would throw a NullPointerException
if e.getValue()
is null, which is why you must have separate logic to handle null.
It's not a matter of performance. It's a matter of correctness.
Upvotes: 4