Java Reference
In-Depth Information
You cannot override
equals()
with arbitrary code. Doing so will probably prove
disastroustoyourapplications.Instead,youneedtoadheretothecontractthatisspeci-
fied in the Java documentation for this method, and which I present next.
The
equals()
methodimplementsanequivalencerelationonnonnullobjectrefer-
ences:
•
It is reflexive
: For any nonnull reference value
x
,
x
.equals(
x
)
returns true.
•
It is symmetric
:Foranynonnullreferencevalues
x
and
y
,
x
.equals(
y
)
re-
turns true if and only if
y
.equals(
x
)
returns true.
•
It is transitive
:Foranynonnullreferencevalues
x
,
y
,and
z
,if
x
.equals(
y
)
returnstrueand
y
.equals(
z
)
returnstrue,then
x
.equals(
z
)
returnstrue.
•
It is consistent
:Foranynonnullreferencevalues
x
and
y
,multipleinvocations
of
x
.equals(
y
)
consistentlyreturntrueorconsistentlyreturnfalse,provided
no information used in
equals()
comparisons on the objects is modified.
• For any nonnull reference value
x
,
x
.equals(null)
returns false.
Althoughthiscontractprobablylookssomewhatintimidating,itisnotthatdifficultto
Listing 2-27.
Logically comparing
Point
objects
class Point
{
private int x, y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}
int getX() { return x; }
int getY() { return y; }
@Override
public boolean equals(Object o)
{
if (!(o instanceof Point))
return false;
Point p = (Point) o;