Java Reference
In-Depth Information
/** Default Constructor */
public
public
EqualsDemo
() {
this
this
(
0
,
new
new
SomeClass
());
}
/** Demonstration "equals" method */
@Override
public
public
boolean
boolean
equals
(
Object o
) {
iif
(
o
==
this
this
)
//
optimization
return
return true
true
;
iif
(
o
==
null
null
)
//
No object ever equals
null
null
return
return false
false
;
// Of the correct class?
iif
(
o
.
getClass
() !=
EqualsDemo
.
class
)
return
return false
false
;
EqualsDemo other
= (
EqualsDemo
)
o
;
// OK, cast to this class
// compare field-by-field
iif
(
int1
!=
other
.
int1
)
// compare primitives directly
false
;
iif
(!
obj1
.
equals
(
other
.
obj1
))
return
return false
// compare objects using their equals
return
return false
false
;
return
return true
true
;
}
}
Optimization: if same object, true by definition. Some say this is a premature optimiza-
tion.
If other object null, false by definition.
Co
mpare class descriptors using ==; see following paragraph.
Op
timization: compare primitives first. May or may not be worthwhile; may be better to
order by those most likely to differ—depends on the data and the usage.
Another common mistake to avoid: note the use of class descriptor equality (i.e.,
o.getClass() != EqualsDemo.class
) to ensure the correct class, rather than via
in-
stanceof
, as is sometimes erroneously done. The reflexive requirement of the
equals()