Is it a bad idea if equals(null) throws NullPointerException instead?
Posted
by polygenelubricants
on Stack Overflow
See other posts from Stack Overflow
or by polygenelubricants
Published on 2010-05-22T10:45:50Z
Indexed on
2010/05/22
10:50 UTC
Read the original article
Hit count: 500
The contract of equals
with regards to null
, is as follows:
For any non-null reference value
x
,x.equals(null)
shouldreturn false
.
This is rather peculiar, because if o1 != null
and o2 == null
, then we have:
o1.equals(o2) // returns false
o2.equals(o1) // throws NullPointerException
The fact that o2.equals(o1) throws NullPointerException
is a good thing, because it alerts us of programmer error. And yet, that error would not be catched if for various reasons we just switched it around to o1.equals(o2)
, which would just "silently fail" instead.
So the questions are:
- Why is it a good idea that
o1.equals(o2)
shouldreturn false
instead of throwingNullPointerException
? - Would it be a bad idea if wherever possible we rewrite the contract so that
anyObject.equals(null)
always throwNullPointerException
instead?
© Stack Overflow or respective owner