Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
hashmap
hashtable
communitycreator

How to use the WeakHashMap.put() method in Java

Programming Bytes

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 WeakReference type 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 key and value must not be null. 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 WeakHashMap
        WeakHashMap<Integer, String> numbers = new WeakHashMap<>();
        
        // Adding key-value pairs to the WeakHashMap
        System.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 map
        System.out.println("The map is " + numbers);
    }
}
Use of WeakHashMap.put()

Explanation

  • 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.

RELATED TAGS

java
hashmap
hashtable
communitycreator
RELATED COURSES

View all Courses

Keep Exploring