Java Reference
In-Depth Information
These object references contain the same values.
How It Works
The comparison operator
(==)
can be used to determine the equality of two objects.
This equality does not pertain to the object values, but rather to the object references.
Often an application is more concerned with the values of objects; in such cases, the
equals()
method is the preferred choice because it compares the values contained
within the objects rather than the object references.
The comparison operator takes a look at the object reference and determines wheth-
er it points to the same object as the object reference that it is being compared against.
If the two objects are equal, a
Boolean true
result will be returned; otherwise, a
Boolean false
result will be returned. In solution 1, the first comparison between
the
team1
object reference and the
team2
object reference returns a false value be-
cause those two objects are separate in memory, even though they contain the same
values. The second comparison in solution 1 between the
team3
object reference and
the
team4
object reference returns a true value because both of those references refer
to the
team1
object.
The
equals()
method can be used to test whether two objects contain the same
values. In order to use the
equals()
method for comparison, the object that is being
compared should override the
Object
class
equals()
and
hashCode()
methods.
The
equals()
method should implement a comparison against the values contained
within the object that would yield a true comparison result. The following code is an
example of an overridden
equals()
method that has been placed into the
Team
ob-
ject:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Team) {
Team other = (Team) obj;
return other.getName().equals(this.getName())
&& other.getCity().equals(this.getCity())
&& other.getPlayers().equals(this.getPlayers());