Java Reference
In-Depth Information
System.out.println(map.get(p1)); // Output: first
point
System.out.println(map.get(new Point(10, 20))); //
Output: null
}
}
y
to local variable
hc
, rather than directly using these fields in the hash code calcula-
tion. However, I decided to follow this approach to more closely mirror the hash code
algorithm.
When you run this application, its last two lines of output are of the most interest.
Insteadofpresenting
first point
followedby
null
ontwoseparatelines,theap-
plicationnowcorrectlypresents
first point
followedby
first point
onthese
lines.
Note
LinkedHashMap
isasubclassof
HashMap
thatusesalinkedlisttostoreits
entries. As a result,
LinkedHashMap
's iterator returns entries in the order in which
they were inserted. For example, if
Listing 5-19
had specified
Map<String, In-
teger> argMap = new LinkedHashMap<>();
,theapplication's outputfor
java HashMapDemo how much wood could a woodchuck chuck if
a woodchuck could chuck wood
would have been
{how=1, much=1,
wood=2, could=2, a=2, woodchuck=2, chuck=2, if=1}
followedby
Number of distinct arguments = 8
.
IdentityHashMap
The
IdentityHashMap
class provides a
Map
implementation that uses reference
equality(
==
)insteadofobjectequality(
equals()
)whencomparingkeysandvalues.
This is an intentional violation of
Map
's general contract, which mandates the use of
equals()
when comparing elements.
IdentityHashMap
obtains hash codes via
System
's
static int iden-
tityHashCode(Object x)
methodinsteadofviaeachkey's
hashCode()
meth-
od.
identityHashCode()
returns the same hash code for
x
as returned by
Ob-
ject
's
hashCode()
method,whetherornot
x
'sclassoverrides
hashCode()
.The
hash code for the null reference is zero.