Java Reference
In-Depth Information
What else could go wrong? Well, what if either
obj1
or
other.obj1
is null? You might have
just earned a nice shiny new
NullPointerException
. So you also need to test for any pos-
sible null values. Good constructors can avoid these
NullPointerException
s, as I've tried
to do in
EqualsDemo
, or else test for them explicitly.
hashCode()
The
hashCode()
method is supposed to return an
int
that should uniquely identify different
objects.
A properly written
hashCode()
method will follow these rules:
It is repeatable.
hashCode(x)
must return the same
int
when called repeatedly, unless set methods have
been called.
It is consistent with equality.
If
x.equals(y)
, then
x.hashCode()
must ==
y.hashCode()
.
Distinct objects should produce distinct hashCodes
If
!x.equals(y)
, it is not required that
x.hashCode()
!=
y.hashCode()
, but doing so
may improve performance of hash tables (i.e., hashes may call
hashCode()
before
equals()
).
The default
hashCode()
on the standard JDK returns a machine address, which conforms to
the first rule. Conformance to the second and third rules depends, in part, on your
equals()
method. Here is a program that prints the hashcodes of a small handful of objects:
public
public class
class
PrintHashCodes
PrintHashCodes
{
/** Some objects to hashCode() on */
protected
protected static
static
Object
[]
data
= {
new
new
PrintHashCodes
(),
new
new
java
.
awt
.
Color
(
0x44
,
0x88
,
0xcc
),
new
new
SomeClass
()
};
public
public static
void
main
(
String
[]
args
) {
System
.
out
.
println
(
"About to hashCode "
+
data
.
length
+
" objects."
);
for
static
void
for
(
int
int
i
=
0
;
i
<
data
.
length
;
i
++) {