Java Reference
In-Depth Information
ensures that the second occurrence of the string literal
"Mickey"
in our program refers to the same
String
instance as the first, so our use of an
IdentityHashMap
in place of a general-purpose
Map
implementation, such as
HashMap
, does not affect the program's behavior. Our naive analysis
neglects two details, but these details effectively cancel each other out.
The important lesson of this puzzle is:
Don't use
IdentityHashMap
unless you need its identity-
based semantics; it is not a general-purpose
Map
implementation.
These semantics are useful for
implementing
topology-preserving object graph transformations
, such as serialization or deep-
copying. A secondary lesson is that string constants are interned. As mentioned in
Puzzle 13
,
programs should rarely, if ever, depend on this behavior for their correct operation.
< Day Day Up >
Search WWH ::
Custom Search