On Equality, part 1

If you write a class, you will probably end up writing an equality comparison method for it. In this post, I will give you my method for writing an equals method in Java. This next post considers the .NET side of things.

One of the most important things you have to consider is that the Object passed to equals method can be anything, not just an instance of the current class. Also, it could be null, so you have to watch for that.

My template for equals is:

public boolean equals(Object anObject) {
  if (this == anObject) {
    return true;
  }
  if ( (anObject != null) &&
    (anObject instanceof <class>) {
      <class> other = (<class>)anObject;
      return ( (this.field1.equals(other.field1) && 
        (this.field2.equals(other.field2) && 
        // compare every field in <class>
        );
  }
  return false;
}

28-12-2004: changed Equals to equals.

Note that I check for reference equality first, so that if it is the same reference, the field-by-field comparison is not required. Next, I check for null, and whether the given object has the same class. Then I cast the object, and finally I return the result of the field-by-field comparison.

Comments are closed.