tunaranch
tunaranch

Reputation: 1586

Comparing references in Java

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

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

Upvotes: 17

Views: 18722

Answers (5)

Molten Ice
Molten Ice

Reputation: 2911

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

Upvotes: 2

Bhimreddy
Bhimreddy

Reputation: 33

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

Upvotes: -1

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

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().

Upvotes: 2

joel.neely
joel.neely

Reputation: 30943

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.

Upvotes: 38

Tim Moore
Tim Moore

Reputation: 9482

That's what the == operator does.

Upvotes: 6

Related Questions