Defining Equals
It's up to each class to decide what makes one object of a class "equal to" another object.
You'll usually follow some common practices when defining an equals method for your class.
- Remember:
equalsshould returnfalseunless the passed reference meets your criteria for equality to the current object.
Basic Sanity Checks¶
Check if the passed reference refers to this object.¶
If the passed reference is a reference to the current object, then of course we are equal.
- This is called the reflexive property of
equals: an object is always equal to itself.
public boolean equals(Object obj) {
if ( obj == this ) { return true; }
return false;
}
Check for null¶
No existing object can be equal to null.
public boolean equals(Object obj) {
if ( obj == this ) { return true; }
if ( obj == null ) { return false; }
return false;
}
Check the passed object's class¶
If the current object is a Giraffe, there's little chance it is "equal to" a referenced Automobile or Employee or String or even Animal object - to be equal to this object the other object needs to specifically be another Giraffe.
- Use the
getClassmethod (defined inObjectand inherited by all classes) to determine the passed object's class.
public boolean equals(Object obj) {
if ( obj == this ) { return true; }
if ( obj == null ) { return false; }
if ( obj.getClass() != this.getClass() ) { return false; }
return false;
}
Compare Object State¶
Once you know you are comparing another object of the same class, the primary purpose of equals is to compare the objects' state.
object state¶
The identifying properties of an object, and their values.
In simple terms, an object's state consists of the values of the instance fields that define the object.
- Remember that the parameter passed to
equalsis of typeObject, so you'll need to cast the reference to the current class in order to compare fields.
public boolean equals(Object obj) {
if ( obj == this ) { return true; }
if ( obj == null ) { return false; }
if ( obj.getClass() != this.getClass() ) { return false; }
MyClass other = (MyClass) obj;
// Now we can compare fields of "this" and "other" to determine equality.
return false;
}
Drill¶
EqualsAndHashcode/com.example.equalsandhashcode.drills.TestNamedObject* Look at theNamedObjectclass and theTestNamedObjectclass. What will be printed when you runTestNamedObject? * InNamedObject, create anequalsmethod that (as shown above) first determines if the passed parameter is a reference to anotherNamedObject, and if so compares itsnamefield to the current object'sname.(Solution: NamedObject.java)