java null != object 和 object!=null 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2938476/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:33:22  来源:igfitidea点击:

what is the difference between null != object and object!=null

java

提问by rozer

Possible Duplicates:
which way is better “null != object” or “ object != null”?
Why does one often see “null != variable” instead of “variable != null” in C#?
‘ … != null’ or ‘null != …’ best performance?

可能的重复:
“null != object”或“object != null”哪个更好?
为什么在 C# 中经常看到“null != variable”而不是“variable != null”?
' ... != null' 或 'null != ...' 最佳性能?

Please guide me. what is the difference between null != object and object!=null
same for "".equal("something") and "something".equals("")

请指导我。null != object 和 object!=null 之间有什么区别
"".equal("something") 和 "something".equals("")

which one is good for processing.

哪个适合加工。

回答by Tim Lloyd

The first two are equivalent, but the "null != object" is an old practice from languages where it is valid to write "if (object = null)" and accidentally assign null to the object. It is a guard to stop this accident from happening.

前两个是等价的,但“null != object”是语言中的一种旧做法,在这种语言中,编写“if (object = null)”并意外地将 null 分配给对象是有效的。它是阻止这次事故发生的警卫。

The second whilst equivalent has the added advantage that if "something" is null you will not get a null reference exception whereas you would if you did: something".equals("").

第二个 while 等效项具有额外的优势,即如果“something”为空,您将不会得到空引用异常,而如果您这样做了:something".equals(""),您将不会得到空引用异常。

回答by polygenelubricants

There is absolutely no difference in either semantics or performance.

在语义或性能上绝对没有区别。

The ==in this case is a reference inequality operation; it can never throw NullPointerException.

==这种情况下是一个参考不等式操作; 它永远不能扔NullPointerException

JLS 15.21.3 Reference Equality Operators == and !=

If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.

The result of !=is falseif the operand values are both nullor both refer to the same object or array; otherwise, the result is true.

JLS 15.21.3 引用相等运算符 == 和 !=

如果相等运算符的操作数都是引用类型或空类型,则该操作是对象相等。

的结果!=false如果操作数值都null或都引用同一个对象或数组;否则,结果为true

Use whatever is most readable. Usually it's something != null.

使用最易读的内容。通常是something != null.

Related questions

相关问题