比较 Java 中的引用

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

Comparing references in Java

java

提问by tunaranch

Let's say that you have overridden an object's equals() and hashCode() methods, so that they use the object's fields.

假设您已经覆盖了对象的 equals() 和 hashCode() 方法,以便它们使用对象的字段。

How you do you check if two references are to the same object, ala the stock equals() method?

您如何检查两个引用是否指向同一个对象,例如股票的 equals() 方法?

回答by joel.neely

Use ==on objects to perform identity comparison.

==在对象上使用以执行身份比较。

That is what the default implementation of equals()does, but one normally overrides equals()to serve as an "equivalent content" check.

这就是 的默认实现equals()所做的,但通常会覆盖equals()以用作“等效内容”检查。

回答by Tim Moore

That's what the == operator does.

这就是 == 运算符所做的。

回答by Vincent Ramdhanie

The default bahaviour of equals() is to compare the two objects using the == operator. So if you want the default bahaviour use ==, if you want your overridden behaviour use equals().

equals() 的默认行为是使用 == 运算符比较两个对象。因此,如果您希望默认行为使用 ==,如果您希望覆盖行为使用 equals()。

回答by Molten Ice

If you need to do this for JUnit Assertion, you can also use Assert.assertSame()

如果您需要为 JUnit 断言执行此操作,您还可以使用 Assert.assertSame()

回答by Bhimreddy

use == Operator because it compares with the reference not with the content, if u want to compare with content u can use equals() method.

使用 == 运算符,因为它与引用而不是内容进行比较,如果您想与内容进行比较,您可以使用 equals() 方法。