null == foo与foo == null [英] null == foo versus foo == null
问题描述
这可能只是一个样式问题,但我正在阅读一本Java编码书('Programming Android')并且编写者在变量方法之前首先声明为null,这是我不熟悉的实践。例如:
This may just be a style question, but I'm reading a Java coding book ('Programming Android') and the writer all declares null first before a variable method, a practice I am not familiar with. For example:
if (null == foo) {
//code here
}
或
if (null != foo) {
//code here
}
而不是
if (foo == null) {
//code here
}
我看不出顺序如何在语义上/语法上产生差异,或者我错在这里?真的很好奇。
I can't see how the order would make a difference semantically/syntactically, or am I wrong here? Really just curious.
推荐答案
这可能是C / C ++遗留下来的习惯。在C中,你会把常量放在左边,因为如果你错误输入 =
而不是 ==
那么会有一个错误,因为您无法将某些内容分配给常量。在Java中,这是不必要的,因为 if(foo = null)
也会产生错误,该错误表示对象引用不是布尔值。
It's probably a habit left over from C/C++. In C, you would put constants on the left, because if you mistyped =
instead of ==
there would be an error because you can't assign something to a constant. In Java, this is unnecessary because if (foo = null)
also gives an error, which says that an object reference isn't a boolean.
这篇关于null == foo与foo == null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!