What is the WeakHashMap.remove(key) method in Java?

WeakHashMap is a kind of Map implemented based on the HashTable. The WeakHashMap only stores WeakReference type as their keys. Once the key is no longer used, the respective mapping will be automatically removed when the garbage collection is done.

In WeakHashMap, we can use the remove method to remove the mapping of the specified key.

Syntax

public V remove(Object key)

Parameters

The key whose mapping is to be removed is passed as an argument.

Return value

  • If there is a mapping present for the specified key, then the mapping is removed and the removed value is returned.

  • If there is no mapping present for the specified key, then null is returned.

Code

The below example shows how to use the remove method.

import java.util.WeakHashMap;
class RemoveExample {
public static void main( String args[] ) {
WeakHashMap<Integer, String> map = new WeakHashMap<>();
map.put(1, "one");
map.put(2, "two");
System.out.println("The map is -" + map );
String returnValue = map.remove(1);
System.out.println("\nThe return value for remove method is -" + returnValue);
System.out.println("The map is -" + map );
returnValue = map.remove(3);
System.out.println("\nThe return value for remove method is -" + returnValue);
System.out.println("The map is -" + map );
}
}

Explanation

In the code above:

  • In line 1, we imported the WeakHashMap class.

  • In line 5, we created a WeakHashMap object with the name map.

  • In lines 6-7, we used the put method to add two mappings ({1=one, 2=two}) to the map object.

  • In line 10, we used the remove method to remove the mapping for the key 1.

  • In line 14, we used the remove method to remove the mapping for the key 3. There is no such entry present, so null will be returned.

Free Resources