Saturday, April 14, 2012

Implementing an equals() Method



                            Overriding equals()

You learned about the equals() method in earlier chapters, where we looked at the wrapper classes. We discussed how comparing two object references using the == operator evaluates to true only when both references refer to the same object (because == simply looks at the bits in the variable, and they're either identical or they're not). You saw that the String class and the wrapper classes have overridden the equals() method (inherited from class Object), so that you could compare two different objects (of the same type) to see if their contents are meaningfully equivalent. If two different Integer instances both hold the int value 5, as far as you're concerned they are equal. The fact that the value 5 lives in two separate objects doesn't matter. 
When you really need to know if two references are identical, use ==. But when you need to know if the objects themselves (not the references) are equal, use the equals() method. For each class you write, you must decide if it makes sense to consider two different instances equal. For some classes, you might decide that two objects can never be equal. For example, imagine a class Car that has instance variables for things like make, model, year, configuration—you certainly don't want your car suddenly to be treated as the very same car as someone with a car that has identical attributes. Your car is your car and you don't want your neighbor Billy driving off in it just because, "hey, it's really the same car; the equals() method said so." So no two cars should ever be considered exactly equal. If two references refer to one car, then you know that both are talking about one car, not two cars that have the same attributes. So in the case of a Car you might not ever need, or want, to override the equals() method. Of course, you know that isn't the end of the story.



                                        Implementing an equals() Method



public class EqualsTest {
public static void main (String [] args) {
Moof one = new Moof(8);
Moof two = new Moof(8);
if (one.equals(two)) {
System.out.println("one and two are equal");
}
}
}
class Moof {
private int moofValue;
Moof(int val) {
moofValue = val;
}
public int getMoofValue() {
return moofValue;
}
public boolean equals(Object o) {
if ((o instanceof Moof) && (((Moof)o).getMoofValue()
== this.moofValue)) {
return true;
} else {
return false;
}
}
}