A==B vs B==A,有什么区别 [英] A==B vs B==A, What are the differences
问题描述
所以长话短说.一位教授在课堂上提出了这个问题作为讨论的开始.除了显而易见的
So to make a long story short. A professor asked this question in class as a discussion starter. Besides the obvious
B = new SomeClass("B"); // But B can be null, can can be new SomeClass("A");
A = new SomeClass("A");
A==B
比较时会保证没有NPE,使用B==A而不是A==B的原因是什么?
will guarantee no NPE when comparing, what are the reasons to use B==A instead of A==B?
其中 A 和 B 属于同一类型,这与语言无关.所以你可以假设 A.equals(B) 用于 Java,或者 C 或 C++ 等中的等效语法......
Where A and B are of same type, and this is language independent. So you can assume A.equals(B) for Java, or equivalent syntax in C or C++ etc....
不,这不是家庭作业.
推荐答案
在 Java 中,A == B
和 B == A
始终具有相同的语义.在 C#(具有运算符重载)中,如果 B
是 A
类的子类的实例,则可能会有所不同.
In Java, A == B
and B == A
always have the same semantics. In C# (which has operator overloading), there can be a difference if, say, B
is an instance of a subclass of the class of A
.
请注意,A.equals(B)
不等同于 A == B
.
Note that A.equals(B)
is not equivalent to A == B
.
这篇关于A==B vs B==A,有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!