How to use the WeakHashMap.put() method in Java
Overview
The WeakHashMap is a kind of a Map whose implementation is based on the HashTable. The WeakHashMap only stores WeakReference type values as its keys. Once the key is no longer used, the respective mapping will be automatically removed when the garbage collection is done.
Note: You can read more about the
WeakReferencetype here.
The put() method maps the passed value to the specified key in the WeakHashMap.
Syntax
public V put(K key,V value)
Parameters
key: The key for which the value is to be mapped.value: This is the value to be associated with the key.
Return value
If the key is already present in the map, then the old value is replaced with the passed value and the old value is returned.
If the key is not present in the map, a new key-value pair is inserted and null is returned.
Note: The arguments
keyandvaluemust not benull. Otherwise,NullPointerExceptionwill be thrown.
The following code demonstrates how to use the put() method.
import java.util.WeakHashMap;class PutExample {public static void main( String args[] ) {// Creating a WeakHashMapWeakHashMap<Integer, String> numbers = new WeakHashMap<>();// Adding key-value pairs to the WeakHashMapSystem.out.println("Adding the entry (1-one). The return value is " + numbers.put(1, "one"));System.out.println("Adding the entry (2-Two). The return value is " + numbers.put(2, "Two"));System.out.println("Adding the entry (1-Three). The return value is " + numbers.put(1, "Three"));//Printing the mapSystem.out.println("The map is " + numbers);}}
Explanation
-
Line 6: We create a
WeakHashMapobject with the namenumbers. -
Lines 9–10: We use the
put()method to add new mappings for the keys1and2, with the valuesoneandtwo, respectively. -
Line 11: We update the value for the key
1with a new value,three. -
Line 14: We print the updated map.