Java 对象==空或空==对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2369226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
object==null or null==object?
提问by Jijoy
I heard from somebody that null == object
is better than object == null
check
我听说有人null == object
比object == null
检查更好
eg :
例如:
void m1(Object obj ) {
if(null == obj) // Is this better than object == null ? Why ?
return ;
// Else blah blah
}
Is there any reasons or this is another myth ? Thanks for help.
有什么原因还是这是另一个神话?感谢帮助。
采纳答案by Laurence Gonsalves
This is probably a habit learned from C, to avoid this sort of typo (single =
instead of a double ==
):
这可能是从 C 中学到的一个习惯,以避免这种类型的错字(single=
而不是 double ==
):
if (object = null) {
The convention of putting the constant on the left side of ==
isn't really useful in Java since Java requires that the expression in an if
evaluate to a boolean
value, so unless the constant is a boolean
, you'd get a compilation error either way you put the arguments. (and if it is a boolean, you shouldn't be using ==
anyway...)
将常量放在 of 左侧的约定==
在 Java中并没有真正有用,因为 Java 要求将 an 中的表达式if
计算为一个boolean
值,因此除非常量是 a boolean
,否则无论您将论据。(如果它是一个布尔值,你==
无论如何都不应该使用......)
回答by Ignacio Vazquez-Abrams
For the same reason you do it in C; assignment is an expression, so you put the literal on the left so that you can't overwrite it if you accidentally use =
instead of ==
.
出于同样的原因,您在 C 中执行此操作;赋值是一个表达式,所以你把文字放在左边,这样如果你不小心使用=
而不是==
.
回答by Chandra Sekar
This is not of much value in Java (1.5+) except when the type of object is Boolean
. In which case, this can still be handy.
这在 Java (1.5+) 中没有多大价值,除非对象的类型是Boolean
. 在这种情况下,这仍然很方便。
if (object = null)
will not cause compilation failure in Java 1.5+ if object is Boolean
but would throw a NullPointerException
at runtime.
if (object = null)
如果对象是Boolean
,则不会在 Java 1.5+ 中导致编译失败,但会NullPointerException
在运行时抛出 a 。
回答by vava
This trick supposed to prevent v = null
kind of typos.
这个技巧应该可以防止v = null
打字错误。
But Java allows only boolean expressions as if()
conditions so that trick does not make much sense, compiler will find those typos anyway.
但是 Java 只允许布尔表达式作为if()
条件,所以这个技巧没有多大意义,编译器无论如何都会发现这些拼写错误。
It is still valuable trick for C/C++ code though.
尽管如此,它仍然是 C/C++ 代码的宝贵技巧。
回答by R Samuel Klatchko
In Java there is no good reason.
在 Java 中没有充分的理由。
A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:
其他几个答案声称这是因为您可能不小心将其分配而不是相等。但是在 Java 中,你必须在 if 中有一个布尔值,所以这个:
if (o = null)
will not compile.
不会编译。
The only time this could matter in Java is if the variable is boolean:
这在 Java 中唯一重要的是变量是否为布尔值:
int m1(boolean x)
{
if (x = true) // oops, assignment instead of equality
回答by Jon Skeet
As others have said, it's a habit learned from C to avoid typos - although even in C I'd expect decent compilers at high enough warning levels to give a warning. As Chandru says, comparing against null in Java in this way would only cause problems if you were using a variable of type Boolean
(which you're not in the sample code). I'd say that's a pretty rare situation, and not one for which it's worth changing the way you write code everywhere else. (I wouldn't bother reversing the operands even in this case; if I'm thinking clearly enough to consider reversing them, I'm sure I can count the equals signs.)
正如其他人所说,这是从 C 中学到的一种避免拼写错误的习惯——尽管即使在 C 中,我也希望有足够高警告级别的体面编译器发出警告。正如 Chandru 所说,以这种方式与 Java 中的 null 进行比较只会在您使用类型变量Boolean
(您不在示例代码中)时出现问题。我会说这是一种非常罕见的情况,并且不值得改变您在其他地方编写代码的方式。(即使在这种情况下,我也不会费心反转操作数;如果我足够清楚地考虑反转它们,我相信我可以计算等号。)
What hasn'tbeen mentioned is that many people (myself certainly included) find the if (variable == constant)
form to be more readable - it's a more natural way of expressing yourself. This is a reason notto blindly copy a convention from C. You should always question practices (as you're doing here :) before assuming that what may be useful in one environment is useful in another.
什么也没有被提及的是,很多人(当然我自己在内)发现的if (variable == constant)
形式可读性更强-这是表达自己的更自然的方式。这是不要盲目地从 C 中复制约定的一个原因。在假设在一个环境中可能有用的东西在另一个环境中有用之前,您应该始终质疑实践(正如您在这里所做的那样:)。
回答by cherouvim
This also closely relates to:
这也与以下密切相关:
if ("foo".equals(bar)) {
which is convenient if you don't want to deal with NPEs:
如果您不想与 NPE 打交道,这很方便:
if (bar!=null && bar.equals("foo")) {
回答by SPee
That is for people who prefer to have the constant on the left side. In most cases having the constant on the left side will prevent NullPointerException to be thrown (or having another nullcheck). For example the String method equals does also a null check. Having the constant on the left, will keep you from writing the additional check. Which, in another way is also performed later. Having the null value on the left is just being consistent.
这适用于喜欢在左侧使用常量的人。在大多数情况下,左侧的常量将防止抛出 NullPointerException(或进行另一个空检查)。例如 String 方法 equals 也做空检查。将常量放在左侧,将阻止您编写额外的支票。其中,以另一种方式也稍后执行。左边的空值只是保持一致。
like:
喜欢:
String b = null;
"constant".equals(b); // result to false
b.equals("constant"); // NullPointerException
b != null && b.equals("constant"); // result to false
回答by Avinash
Compare with the following code:
与以下代码进行比较:
String pingResult = "asd";
long s = System.nanoTime ( );
if ( null != pingResult )
{
System.out.println ( "null != pingResult" );
}
long e = System.nanoTime ( );
System.out.println ( e - s );
long s1 = System.nanoTime ( );
if ( pingResult != null )
{
System.out.println ( "pingResult != null" );
}
long e1 = System.nanoTime ( );
System.out.println ( e1 - s1 );
Output (After multiple executions):
输出(多次执行后):
null != pingResult
325737
pingResult != null
47027
Therefore, pingResult != null
is the winner.
因此,pingResult != null
是赢家。
回答by Benny Bottema
Because of its commutative property, the only difference between object == null
and null == object
(the Yoda version) is of cognitive nature: how the code is read and digested by the reader. I don't know the definitive answer though, but I do know I personally prefer comparing the object I'm inspecting to something else, rather than comparing something else to the object I'm inspecting, if that makes any sense. Start with the subject, then the value to compare it to.
由于它的可交换属性,object == null
和null == object
(尤达版本)之间的唯一区别是认知性质的:读者如何阅读和消化代码。我不知道确切的答案,但我知道我个人更喜欢将我正在检查的对象与其他对象进行比较,而不是将其他对象与我正在检查的对象进行比较,如果这有意义的话。从主题开始,然后是要与之进行比较的值。
In some other languages this comparison style is more useful.
在其他一些语言中,这种比较风格更有用。
To safe guard against a missing "=" sign in general though, I think writing null == object
is a misguided act of defensive programming. The better way around this particular code is by guaranteeing the behavior with a junit test. Remember, the possible mistake of missing an "=" is not dependant on the method's input arguments - you are not dependent on the right use of this API by other people - so a junit test is perfect to safe guard against that instead. Anyway you will want to write junit tests to verify the behavior; a missing "=" naturally falls within scope.
总体而言,为了防止丢失“=”符号,我认为编写null == object
是防御性编程的一种误导行为。解决此特定代码的更好方法是使用 junit 测试来保证行为。请记住,缺少“=”的可能错误不依赖于方法的输入参数——您不依赖于其他人正确使用此 API——因此,junit 测试非常适合防止这种情况发生。无论如何,您将需要编写 junit 测试来验证行为;缺少的“=”自然属于范围。