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:
o1.equals(o2)
should return false
instead of throwing NullPointerException
?anyObject.equals(null)
always throw NullPointerException
instead?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
?
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?
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 testequals(null)
should throw NullPointerException
Applications should throw instances of this class to indicate other illegal uses of the null object. Read the last sentence again: "Applications should throw instances of this class to indicate other illegal uses of the null object".
Code Correctness: null Argument to equals()equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null . (If the object is null , the program will throw a NullPointerException ).
The equals() method is a static method of the Objects class that accepts two objects and checks if the objects are equal. If both the objects point to null , then equals() returns true .
Bonus: Using Apache CommonsThe equals() method of StringUtils class is a null-safe version of the equals() method of String class, which also handles null values.
To the question of whether this asymmetry is inconsistent, I think not, and I refer you to this ancient Zen kōan:
At that moment, the compiler reached enlightenment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With