Java WeakHashMap
In Java, WeakHashMap
is a class that implements the Map
interface and provides a key-value based data structure. It is part of the java.util
package and is similar to the HashMap
class, except that it uses weak references to its keys.
A weak reference is a type of reference that does not prevent the object that it refers to from being garbage collected. When the key of a mapping in a WeakHashMap
is no longer strongly reachable from the application code (i.e., there are no strong references to the key), the mapping is automatically removed from the WeakHashMap
.
Here are some of the most commonly used methods in the WeakHashMap
class:
void clear()
: This method removes all the key-value mappings from theWeakHashMap
.boolean containsKey(Object key)
: This method returnstrue
if theWeakHashMap
contains a mapping for the specified key, otherwisefalse
.boolean containsValue(Object value)
: This method returnstrue
if theWeakHashMap
contains one or more mappings to the specified value, otherwisefalse
.Set<Map.Entry<K, V>> entrySet()
: This method returns aSet
view of the key-value mappings in theWeakHashMap
.V get(Object key)
: This method returns the value to which the specified key is mapped, ornull
if the key is not mapped to any value.boolean isEmpty()
: This method returnstrue
if theWeakHashMap
contains no key-value mappings, otherwisefalse
.Set<K> keySet()
: This method returns aSet
view of the keys in theWeakHashMap
.V put(K key, V value)
: This method associates the specified value with the specified key in theWeakHashMap
. If theWeakHashMap
previously contained a mapping for the key, the old value is replaced with the new value and the old value is returned.void putAll(Map<? extends K, ? extends V> m)
: This method copies all of the mappings from the specifiedMap
to thisWeakHashMap
.V remove(Object key)
: This method removes the mapping for the specified key from theWeakHashMap
, if it is present.int size()
: This method returns the number of key-value mappings in theWeakHashMap
.Collection<V> values()
: This method returns aCollection
view of the values in theWeakHashMap
.
The use of weak references in WeakHashMap
can be useful in certain situations where the keys are temporary or the application code does not need to maintain strong references to them. However, it can also make the behavior of WeakHashMap
harder to predict, since the mappings can be removed at any time by the garbage collector.