问题描述
equals
对于null
,如下:
对于任何非空引用值x
,x.equals(null)
应该return false
.
这很奇怪,因为如果 o1 != null
和 o2 == null
,那么我们有:
This is rather peculiar, because if o1 != null
and o2 == null
, then we have:
o1.equals(o2) // returns false
o2.equals(o1) // throws NullPointerException
o2.equals(o1) 抛出 NullPointerException
的事实是一件好事,因为它提醒我们程序员的错误.然而,如果出于各种原因,我们只是将其切换到 o1.equals(o2)
,则该错误将不会被捕获,这将默默地失败"相反.
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.
所以问题是:
- 为什么
o1.equals(o2)
应该return false
而不是抛出NullPointerException
是个好主意? - 如果我们尽可能地重写合约,以便
anyObject.equals(null)
总是抛出NullPointerException
,这不是一个坏主意吗?
- 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?
相比之下,这就是可比
合同说:
In contrast, this is what the Comparable
contract says:
注意 null
不是任何类的实例,并且 e.compareTo(null)
应该抛出一个 NullPointerException
即使 e.equals(null)
返回 false
.
如果NullPointerException
适用于compareTo
,为什么它不适用于equals
?
If NullPointerException
is appropriate for compareTo
, why isn't it for equals
?
这些是 Object.equals(Object obj)
文档:
These are the actual words in the Object.equals(Object obj)
documentation:
指示某个其他对象是否等于"这个.
什么是对象?
一个对象是一个类实例或一个数组.
引用值(通常只是references)是指向这些对象的指针,以及一个特殊的null
引用,它不指向任何对象.
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
测试某个其他对象是否等于"这个
null
引用没有为测试提供其他对象- 因此,
equals(null)
应该抛出NullPointerException
equals
tests whether some other object is "equal to"this
null
reference gives no other object for the test- Therefore,
equals(null)
should throwNullPointerException
推荐答案
对于这种不对称是否不一致的问题,我觉得不是,请参考这个古老的禅宗公案:
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.
这篇关于如果 equals(null) 抛出 NullPointerException 是不是一个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!