null and the symmetry of equals [closed]
Equality is supposed to be symmetric, right?
Object someObject = new Object();
Object NULL = null;
NULL.equals(someObject) => NullPointerException
someObject.equals(NULL) => false
What is the rationa开发者_Python百科le for not having the second form throw a NullPointerException
?
In the first case, the equals() method doesn't throw the NPE, so you can't make that argument. Symmetry is part of the contract of the equals() method.
Equality is certainly defined to be symmetric in a theoretical sense, but it also isn't defined at all on non-existent objects (which is what null represents).
Hence any behaviour when applied to null would be equally valid. It could return a live rabbit and still not contradict the theoretical definition of equality.
In such a case, it's a pretty reasonable implementation decision on behalf of the designers of Java that calling equals on a null value should throw a NullPointerException, as that is consistent with calling any other method on a null value.
Because you are not accessing a method of a null
object in the second case. It's not the concept of equality that is unbalanced it's how you are accessing it.
The second example is not an example of symmetry because it violates one of the simple rules in regards to Object and the equals() method:
For any non-null reference value x, x.equals(null) should return false.
I would go for
someObject.equals(null);
What is the rational for not having the second form throw a NullPointerException?
In this case, it won't throw NullPointerException.
Here we are sure that the object on which equals()
is going to invoke is NOT NULL
.
The second bit doesn't throw an NPE because you are not dereferencing a null pointer. That code returns false because you are comparing a value to a non-value.
equals(null)
will always return false because there is no such thing as a null value. Neither Object nor primitive can have the value null
since the concept doesn't exist in Java. null
is a literal that represents the null reference which is why we compare references, such as if (obj == null)
. See the Java language spec, section 3.10.7. In other words, you are comparing the value of someObject
to the null reference.
You could make your own object, override equals
, and return true but that would go against the definition in Object.
精彩评论