对象==空或空==对象? [英] object==null or null==object?
问题描述
我听某人说null == object
比object == null
检查
例如:
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.
推荐答案
这可能是从 C 学到的一个习惯,为了避免这种类型的错字(单个 =
而不是双 ==
):
This is probably a habit learned from C, to avoid this sort of typo (single =
instead of a double ==
):
if (object = null) {
将常量放在 ==
左侧的约定在 Java 中并没有真正有用,因为 Java 要求 if
中的表达式计算为 boolean
值,因此除非常量是 boolean
,否则无论采用哪种方式放置参数,都会出现编译错误.(如果它是一个布尔值,你不应该使用 ==
反正...)
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...)
这篇关于对象==空或空==对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!