java.util.WeakHashMap.put() Method



The put(Object key,Object value) method is used to associate the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced by the new value.


Following is the declaration for java.util.WeakHashMap.put() method.

public Object put(Object key,Object value)


  • key − This is the key with which the specified value is to be associated.

  • value − This is the value to be associated with the specified key.

Return Value

The method call returns the previous value associated with the specified key, or null if there was no mapping for the key.




The following example shows the usage of java.util.WeakHashMap.put() method.

package com.tutorialspoint;

import java.util.Map;
import java.util.WeakHashMap;

public class WeakHashMapDemo {
   public static void main(String[] args) { 
      Map<String, String> weakHashMap = new WeakHashMap<String, String>();

      // put keys and values in the Map
      System.out.println("Putting values into the Map");
      weakHashMap.put("1", "first");
      weakHashMap.put("2", "two");
      weakHashMap.put("3", "three");

      // checking Map
      System.out.println("Map: "+weakHashMap);

      // putting value at key 2
      String str = (String)weakHashMap.put("2", "newvalue");
      System.out.println("Returned value: "+str);
      System.out.println("New Map: "+weakHashMap);

Let us compile and run the above program, this will produce the following result.

Putting values into the Map
Map: {1=first, 2=two, 3=three}
Returned value: two
New Map: {1=first, 2=newvalue, 3=three}