Name
WeakHashMap<K,V>
Synopsis
This class implements
Map
using an internal hashtable. It is similar in
features and performance to HashMap
, except that
it uses the capabilities of the java.lang.ref
package, so that the key-to-value mappings it maintains do not
prevent the key objects from being reclaimed by the garbage
collector. When there are no more references to a key object except
for the weak reference maintained by the
WeakHashMap
, the garbage collector reclaims the
object, and the WeakHashMap
deletes the mapping
between the reclaimed key and its associated value. If there are no
references to the value object except for the one maintained by the
WeakHashMap
, the value object also becomes
available for garbage collection. Thus, you can use a
WeakHashMap
to associate an auxiliary value with
an object without preventing either the object (the key) or the
auxiliary value from being reclaimed. See HashMap
for a discussion of the implementation features of this class. See
Map
for a description of the methods it defines.
WeakHashMap
is
primarily useful with objects whose equals( )
methods use the ==
operator for comparison. It is
less useful with key objects of type String
, for
example, because there can be multiple String
objects that are equal to one another and, even if the original key
value has been reclaimed by the garbage collector, it is always
possible to pass a String
with the same value to
the get( )
method.
Figure 16-69. java.util.WeakHashMap<K,V>
public class WeakHashMap<K,V> ...
Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.