Page 287 - Introduction to Programming with Java: A Problem Solving Approach
P. 287
if (car1 == car2)
{
}
else
{
}
System.out.println("different");
System.out.println("the same");
It prints “the same” because car1 and car2 hold the same value—the address of the lone Car object. But if you want to see if two different objects have the same instance-variable values, the == operator is not what you want. For example, what does this code print?
Car car1 = new Car();
Car car2 = new Car();
car1.setColor("red");
car2.setColor("red");
7.4 Testing Objects for Equality 253
{
}
Apago PDF Enhancer
System.out.println("different");
The car1 == car2 expression returns false. Why? System.out.println("the same");
if (car1 == car2)
{
}
else
Thiscodeprints“different”becausecar1 == car2returnsfalse.Itdoesn’tmatterthatcar1and car2 contain the same data (red). The == operator doesn’t look at the object’s data; it just looks at whether the two reference variables point to the same object. In this case, car1 and car2 refer to distinct objects, with different storage locations in memory.
The equals Method
If you want to see whether two different objects have the same characteristics, you need to compare the contents of two objects rather than just whether two reference variables point to the same object. To do that, you need an equals method in the object’s class definition that compares the two objects’
instance variables. Having such an equals method is very common since you often want
to test two objects to see whether they have the same characteristics. For Java’s API classes, use the classes’ built-in equals methods. For example, in comparing the contents of two strings, call the String class’s equals method. For classes that you implement yourself, adopt the habit of writing your own equals methods.
An Example
The following diagram depicts two objects with identical instance variable values. Comparing nathanCar to nickCar with the == operator generates false, because the two reference variables point to different objects. However, comparing nathanCar to nickCar with a standard equals method generates true, because a standard equals method compares instance variable values, and these two objects have identi- cal instance variable values.
An equals method is a handy utility.