如果equals(null)抛出NullPointerException,这是一个坏主意吗? [英] Is it a bad idea if equals(null) throws NullPointerException instead?
问题描述
null 的noreferrer> 等于
,如下所示:
The contract of equals
with regards to null
, is as follows:
对于任何非空引用值
x
,x.equals(null)
应该返回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.
所以问题是:
- 为什么<$ c是个好主意$ c> o1.equals(o2)应该
返回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)
应抛出NullPointerExce ption
即使e.equals(null)
返回false
。
Note that
null
is not an instance of any class, ande.compareTo(null)
should throw aNullPointerException
even thoughe.equals(null)
returnsfalse
.
如果 NullPointerException
适用于 compareTo
,为什么不是等于
?
If NullPointerException
is appropriate for compareTo
, why isn't it for equals
?
- Comparable and Comparator contract with regards to null
这些是 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.
-
等于
测试某些其他对象是否等于此
-
null
reference为测试提供其他对象 - 因此,
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
推荐答案
关于这种不对称是否不一致的问题,我想不是,我推荐你这个古老的禅kōan:
To the question of whether this asymmetry is inconsistent, I think not, and I refer you to this ancient Zen kōan:
- 询问任何一个男人他是否像他一样od作为下一个男人,每个人都会说是。
- 询问任何一个人是否和没有人一样好,每个人都会说不。
- 问一个人是否和任何男人一样好,你会永远不会得到答复。
此时,编制者已达到启示。
At that moment, the compiler reached enlightenment.
这篇关于如果equals(null)抛出NullPointerException,这是一个坏主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!