Java Reference
In-Depth Information
b. If f isofbyteinteger,character,integer,orshortintegertype,calculate
hc = (int) f . The integer value is the hash code.
c. If f isoflongintegertype,calculate hc = (int) (f^(f>>>32)) .
This expression exclusive ORs the long integer's least significant 32
bits with its most significant 32 bits.
d. If f is of type floating-point, calculate hc =
Float.floatToIntBits(f) .Thismethodtakes+infinity,-infin-
ity, and NaN into account.
e. If f is of type double precision floating-point, calculate long l
(l^(l>>>32)) .
f. If f is a reference field with a null reference, calculate hc = 0 .
g. If f isareferencefieldwithanonnullreference,andif X 's equals()
method compares the field by recursively calling equals() (as in
Listing 5-12 ' s Employee class), calculate hc = f.hashCode() .
However, if equals() employs a more complex comparison, create
a canonical (simplest possible) representation of the field and call
hashCode() on this representation.
h. If f isanarray,treateachelementasaseparatefieldbyapplyingthisal-
gorithmrecursivelyandcombiningthe hc valuesasshowninthenext
3. Combine hc with hashCode as follows: hashCode =
hashCode*31+hc .Multiplying hashCode by 31 makestheresultinghash
value dependent on the order in which fields appear in the class, which im-
eral int s, for example). I chose 31 to be consistent with the String class's
hashCode() method.
4. Return hashCode from hashCode() .
Tip Instead of using this or another algorithm to create a hash code, you might
find it easier to work with the HashCodeBuilder class (see ht-
lang/builder/HashCodeBuilder.html foranexplanationofthisclass).This
class, which follows Bloch's rules, is part of the Apache Commons Lang component,
which you can download from .
Search WWH ::

Custom Search