The equals() method

The equals() method of java.lang.Object acts the same as the == operator; that is, it tests for object identity rather than object equality. The implicit contract of the equals() method, however, is that it tests for equality rather than identity. Thus most classes will override equals() with a version that does field by field comparisons before deciding whether to return true or false.

To elaborate, an object created by a clone() method (that is a copy of the object) should pass the equals() test if neither the original nor the clone has changed since the clone was created. However the clone will fail to be == to the original object.

For example, here is an equals() method you could use for the Car class. Two cars are equal if and only if their license plates are equal, and that's what this method tests for.

 public boolean equals(Object o) {
  
    if (o instanceof Car) {
      Car c = (Car) o;
      if (this.licensePlate.equals(c.licensePlate)) return true;
    }
    return false;
    
  }

This example is particularly interesting because it demonstrates the impossibility of writing a useful generic equals() method that tests equality for any object. It is not sufficient to simply test for equality of all the fields of two objects. It is entirely possible that some of the fields may not be relevant to the test for equality as in this example where changing the speed of a car does not change the actual car that's referred to.

Be careful to avoid this common mistake when writing equals() methods:

 public boolean equals(Car c) {
  
    if (o instanceof Car) {
      Car c = (Car) o;
      if (this.licensePlate.equals(c.licensePlate)) return true;
    }
    return false;
    
  }

The equals() method must allow tests against any object of any class, not simply against other objects of the same class (Car in this example.)

You do not need to test whether o is null. null is never an instance of any class. null instanceof Object returns false.


Previous | Next | Top | Cafe au Lait

Copyright 1997-1999, 2001 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified November 2, 2001