Java Collection Tutorial - Java WeakHashMap.put(K key, V value)


WeakHashMap.put(K key, V value) has the following syntax.

public V put(K key, V value)


In the following code shows how to use WeakHashMap.put(K key, V value) method.

/*w w  w .ja v  a 2  s.  c  om*/
import java.util.Map;
import java.util.WeakHashMap;

public class Main {
   public static void main(String[] args) { 
      Map<String, String>  weakHashMap = new WeakHashMap<String, String> ();
      System.out.println("Putting values into the Map");
      weakHashMap.put("1", "first");
      weakHashMap.put("2", "two");
      weakHashMap.put("3", "from");
      // 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);

The code above generates the following result.