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
WeakReference
type here.
The put()
method maps the passed value to the specified key in the WeakHashMap
.
public V put(K key,V value)
key
: The key for which the value is to be mapped.value
: This is the value to be associated with the key.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
key
andvalue
must not benull
. Otherwise,NullPointerException
will 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);}}
Line 6: We create a WeakHashMap
object with the name numbers
.
Lines 9–10: We use the put()
method to add new mappings for the keys 1
and 2
, with the values one
and two
, respectively.
Line 11: We update the value for the key 1
with a new value, three
.
Line 14: We print the updated map.