19

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?

5 Answers 5

41

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, most equals operations perform the this == obj check, because obviously if they are referencing the same object, then equals will return true (assuming equals works :))
8

That's what the == operator does.

Comments

3

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

Comments

2

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

Comments

-1

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

1 Comment

This appears to be just a repeat of the existing answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.