Showing posts with label Java Basics. Show all posts
Showing posts with label Java Basics. Show all posts

Monday, February 9, 2009

Implementing the equals() Method

This short article contains the recent facts for implementing the equals() method of a class. If you are interested in the full explanation of the details, please take a look at the article from Angelika Langer: Implementing the equals() Method - Part 1 (german only, sorry).

This is the basic implementation for a class that is directly derived from java.lang.Object:
public boolean equals(final Object object) {
if (this == object) {
return true;
}

if (object == null) {
return false;
}

if (getClass() != object.getClass()) {
return false;
}

// TODO compare all fields of this class
return true;
}
This is the basic implementation for a class that is NOT directly derived from java.lang.Object:
public boolean equals(final Object object) {
if (this == object) {
return true;
}

if (!super.equals(object)) {
return false;
}

// TODO compare all fields of this class
return true;
}