Implementing the equals
method of a Java class is an often discussed topic. In general you want to ensure, that the method returns true
, if:
- the object you compare
this
with is the same object regarding the pointer (object == this) or
- the object you compare
this
with is the same regarding your domain
So regarding your question, you ask for the former case, in which Java just checks if the object
passed and this
are pointing to the same address in memory (maybe this link helps you http://www.javaworld.com/article/2072762/java-app-dev/object-equality.html).
A short note: When you implement the equals
method you normally follow this pattern:
check if you have the same object (regarding pointers), i.e.
if (object == this) return true;
you make sure that you don't have any null
instance (to avoid further NullPointerException
and if it's null
it can never be equal, i.e.,
else if (object == null) return false;
you check if the object is equal regarding whatever equal means in your domain (e.g., a dao might be assumed to be equal if the id
is equal); prior to doing the domain specific validation, you normally always make sure that you have an object of the correct instance, i.e.,
else if (this.getClass().equals(obj.getClass()) { ... }
or
else if (this.getClass().isInstance(obj.getClass()) { ... }
in all other cases you want to return false, i.e.,
else return false;
NOTE:
When implementing the equals
method it is often useful to use the Objects.equals(...)
method to compare the different attributes of the instances.
EXAMPLE:
@Override
public boolean equals(final Object obj) {
if (obj == this) {
// we have the same object regarding the pointers (e.g., this.equals(this)), or have a look at 'Manjunath M' post for a different example
return true;
} else if (obj == null) {
// we compare with null (e.g., this.equals(null))
return false;
} else if (Contact.class.isInstance(obj.getClass())) {
/*
* If you want to be more strict you could also use:
* getClass().equals(obj.getClass())
*/
Contact other = Contact.class.cast(obj);
return Objects.equals(other.getFirstName(), getFirstName()) &&
Objects.equals(other.getLastName(), getLastName()) &&
Objects.equals(other.getHomePhone(), getHomePhone()) &&
Objects.equals(other.getCellPhone(), getCellPhone());
} else {
return false;
}
}