Java Utility Library

Java WeakHashMap - put() Method



The java.util.WeakHashMap.put() method is used to associate the specified value with the specified key in the map. If the key is already present in the map, the old value is replaced.

Syntax

public V put(K key, V value)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key with which the specified value is to be associated.
value Specify the value to be associated with the specified key.

Return Value

Returns previous value associated with given key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

Exception

NA

Example:

In the example below, the java.util.WeakHashMap.put() method is used to associate key-value pairs in the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a weakhashmap
    WeakHashMap<Integer, String> MyMap = new WeakHashMap<Integer, String>();

    //populating the map
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");

    //printing the map
    System.out.println("MyMap contains: " + MyMap);    

    //change a key-value pair
    MyMap.put(103, "Ramesh"); 

    //printing the map
    System.out.println("MyMap contains: " + MyMap);  
  }
}

The output of the above code will be:

MyMap contains: {104=Jo, 101=John, 103=Kim, 102=Marry}
MyMap contains: {104=Jo, 101=John, 103=Ramesh, 102=Marry}

❮ Java.util - WeakHashMap