Java Reference
In-Depth Information
1
class BaseClass
2
{
3
public BaseClass( int i )
4
{ x = i; }
5
6
public boolean equals( Object rhs )
7
{
8
if( rhs == null || getClass( ) != rhs.getClass( ) )
9
return false;
10
11
return x == ( (BaseClass) rhs ).x;
12
}
13
14
private int x;
15
}
16
17
class DerivedClass extends BaseClass
18
{
19
public DerivedClass( int i, int j )
20
{
21
super( i );
22
y = j;
23
}
24
25
public boolean equals( Object rhs )
26
{
27
// Class test not needed; getClass() is done
28
// in superclass equals
29
return super.equals( rhs ) &&
30
y == ( (DerivedClass) rhs ).y;
31
}
32
33
private int y;
34
}
figure 6.34
Correct
implementation of
equals
When using a
HashSet
, we must also override the special
hashCode
method
that is specified in
Object
;
hashCode
returns an
int
. Think of
hashCode
as pro-
viding a trusted hint of where the items are stored. If the hint is wrong, the
item is not found, so if two objects are equal, they should provide identical
hints. The contract for
hashCode
is that if two objects are declared equal by
the
equals
method, then the
hashCode
method must return the same value for
them. If this contract is violated, the
HashSet
will fail to find objects, even if
equals
declares that there is a match. If
equals
declares the objects are not
equal, the
hashCode
method should return a different value for them, but this
is not required. However, it is very beneficial for
HashSet
performance if
hashCode
rarely produces identical results for unequal objects. How
hashCode
and
HashSet
interact is discussed in Chapter 20.
The
hashCode
method must be
overridden, if
equals
is overrid-
den, or the
HashSet
will not work.
Search WWH ::
Custom Search