== 原始数据类型运算符
我试图理解 Java 中 == 和 equals to 运算符之间的区别。 例如 == 会检查是否是同一个对象,而 equals 会比较对象的值...那么为什么我们使用 == 来比较 int 等基本数据类型。 因为如果我有
int i =7; //and
int j = 6.
它们不是同一个对象,并且堆栈中的内存地址也不同。或者 == 对于基元比较的行为是否有所不同??
Possible Duplicate:
How Does the toString(), ==, equals() object methods work differently or similarly on reference and primitive types?
I am trying to understand the difference between == and equals to operator in Java.
e.g. == will check if it is the same object while equals will compare the value of the object ... Then why do we use == for comparing primitive data types like int.
Because if I have
int i =7; //and
int j = 6.
They are not the same object and not the same memory address in stack. Or does the == behaves differently for primitives comparison.??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,== 对于所有变量的行为都是相同的:它测试这些变量的值是否相等。对于
Object obj
,obj
是对象的引用。由于==
测试两个对象引用是否具有相同的值,因此它正在测试它们是否引用相同的对象(即引用是否相等)。Actually, == behaves identically for all variables: it tests whether the values of those variables are equal. In the case of
Object obj
,obj
is a reference to an object. Since==
tests whether two object references have the same value, it is testing whether they refer to the identical object (i.e., that the references are equal).==
在原始类型上的直观工作方式有所不同。语言就是这样。如果您用 C++ 术语来思考,引用就是指针,而
==
进行指针比较。==
intuitively work differently on primitive types. Its just that way in the language.If you think about it in C++ terms, references are pointers and
==
does pointer comparison.