Java Reference
In-Depth Information
"+argMap.size());
}
}
HashMapDemo createsahashmapof String keysand Integer values.Eachkey
is one of the command-line arguments passed to this application, and its value is the
number of occurrences of that argument on the command line.
Forexample, java HashMapDemo how much wood could a woodchuck
chuck if a woodchuck could chuck wood generates the following output:
{wood=2, could=2, how=1, if=1, chuck=2, a=2, woodchuck=2,
much=1}
Number of distinct arguments = 8
Because the String class overrides equals() and hashCode() , Listing 5-19
canuse String objectsaskeysinahashmap.Whenyoucreateaclasswhoseinstances
are to be used as keys, you must ensure that you override both methods.
Listing 5-6 showed you that a class's overriding hashCode() method can call a
referencefield's hashCode() methodandreturnitsvalue,providedthattheclassde-
clares a single reference field (and no primitive type fields).
More commonly, classes declare multiple fields, and a better implementation of the
hashCode() method is required. The implementation should try to generate hash
codes that minimize collisions.
There is no rule on how to best implement hashCode() , and various algorithms
(recipes for accomplishing tasks) have been created. My favorite algorithm appears
in Effective Java Second Edition , by Joshua Bloch (Addison-Wesley, 2008; ISBN:
0321356683).
Thefollowingalgorithm,whichassumestheexistenceofanarbitraryclassthatisre-
ferred to as X , closely follows Bloch's algorithm, but is not identical:
1. Initialize int variable hashCode (the name is arbitrary) to an arbitrary
nonzerointegervalue,suchas19.Thisvariableisinitializedtoanonzerovalue
toensurethatittakesintoaccountanyinitialfieldswhosehashcodesarezeros.
Ifyouinitialize hashCode to0,thefinalhashcodewillbeunaffectedbysuch
fields and you run the risk of increased collisions.
2. Foreachfield f thatisalsousedin X 's equals() method,calculate f 'shash
code and assign it to int variable hc as follows:
a. If f is of Boolean type, calculate hc = f?1:0 .
Search WWH ::




Custom Search