Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 4 ■ OPERATORS


Implementing the equals Method


The first comparison is to see whether one object is equal to another. As we saw previously, the equality
and inequality operators determine only whether two objects use the same object reference (that is, the
same place in memory). Consequently, two different objects, each with its own memory address, are
never equal. The following class might help illustrate the issue (see Listing 4-27).

Listing 4-27. Using the equality operator with objects

package com.apress.javaforabsolutebeginners .examples.comparing;

public class CompareTest {

public static void main(String[] args) {
Object a = new Object();
Object b = new Object();
Object c = b;
System.out.println(a == b);
System.out.println(b == c);
}

}

That code prints “false” for the first comparison and “true” for the second. In essence, we create a
single object with two names (b and c), so the second comparison yields a value of “true.” The new
keyword offers a big hint here. For c, we don’t create a new object, just another reference to an existing
one. To see whether two objects are equal, we have to compare objects that implement the equals
method. Let's return to our Person class and expand it to have an equals method (see Listing 4-28).

Listing 4-28. Person class with equals method

package com.apress.javaforabsolutebeginners .examples.comparing;

public class Person {
String firstName;
String lastName;

public Person (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

public boolean equals(Person p) {
if (p == null) {
return false;
}
if (p == this) {
return true;
}
Free download pdf