Is it a bad idea if equals(null) throws NullPointerException instead?
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?
On comparison with Comparable
In contrast, this is what the Comparable
contract says:
Note that
null
is not an instance of any class, ande.compareTo(null)
should throw aNullPointerException
even thoughe.equals(null)
returnsfalse
.
If NullPointerException
is appropriate for compareTo
, why isn't it for equals
?
Related questions
- Comparable and Comparator contract with regards to null
A purely semantical argument
These are the actual words in the Object.equals(Object obj)
documentation:
Indicates whether some other object is "equal to" this one.
And what is an object?
JLS 4.3.1 Objects
An object is a class instance or an array.
The reference values (often just references) are pointers to these objects, and a special
null
reference, which refers to no object.
My argument from this angle is really simple.
-
equals
tests whether some other object is "equal to"this
-
null
reference gives no other object for the test - Therefore,
equals(null)
should throwNullPointerException
Solution 1:
To the question of whether this asymmetry is inconsistent, I think not, and I refer you to this ancient Zen kōan:
- Ask any man if he's as good as the next man and each will say yes.
- Ask any man if he's as good as nobody and each will say no.
- Ask nobody if it's as good as any man and you'll never get a reply.
At that moment, the compiler reached enlightenment.
Solution 2:
An exception really should be an exceptional situation. A null pointer might not be a programmer error.
You quoted the existing contract. If you decide to go against convention, after all this time, when every Java developer expects equals to return false, you'll be doing something unexpected and unwelcome that will make your class a pariah.
I could't disagree more. I would not rewrite equals to throw an exception all the time. I'd replace any class that did that if I were its client.