I am looking at the equals method, and I see this
and I don't understand what it means...I do understand them when I see it in constructors and some methods but its not clear to me when they are in equals method something like this:
(obj == this)
...what does this mean here ? where does it come from ?
I understand when it says something like this.name = name;
from a method like this
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; }
sorry it might be a duplicate but I couldnt find anything...
this
is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.
You are comparing two objects for equality. The snippet:
if (obj == this) { return true; }
is a quick test that can be read
"If the object I'm comparing myself to is me, return true"
. You usually see this happen in equals
methods so they can exit early and avoid other costly comparisons.
this
refers to the current instance of the class (object) your equals-method belongs to. When you test this
against an object, the testing method (which is equals(Object obj)
in your case) will check wether or not the object is equal to the current instance (referred to as this
).
An example:
Object obj = this; this.equals(obj); //true Object obj = this; new Object().equals(obj); //false
Source: Stackoverflow.com