0

以前は「 anObject != null 」のようにJavaコードのテスト文を書いていましたが、逆に「 null != anObject 」のように書いている人もいました。では、それらの違いは何ですか?Javaでどちらがより良い方法ですか?

4

4 に答える 4

7

Their reasoning is that if you accidentally forget the !, then you have an assignment instead of a comparison, which cannot happen the second way.

anObject = null assigns null to anObject, while null = anObject will produce a compiler error.

于 2013-06-28T13:53:14.177 に答える
3

これは、ヨーダの条件に多少関連しています。

"the force".equals(myString);

myString が null の場合、null ポインターを回避します。

于 2013-06-28T13:54:16.307 に答える
2

It's a style of how people compare expressions.

Do not use null != anObject as null is a constant and is considered a Yoda condition.

Always put the variable left hand side and the constant on the right.

于 2013-06-28T13:53:33.433 に答える
1

From a compiled code point of view there is no difference.

However from a paranoid-programmer point of view it can prevent you from making the dreaded assignment bug.

e.g. if you mistype:

null = myObject

you get a compiler error because you cannot assign to constant.

However if you mistype:

myObject = null

the compiler will not complain. And you may release code that assigns null to your Object instead of testing for null.

于 2013-06-28T13:53:05.223 に答える