17

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

38

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.

1
  • 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 :)) Oct 20, 2008 at 4:19
6

That's what the == operator does.

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

1

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.