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

WeakHashMap is a kind of Map implemented and 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, only if the specified key-value mapping is present.

Syntax

public boolean remove(Object key, Value v)

Argument

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

Return value

This method returns true if the mapping was removed.

Code

The following 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 );
System.out.println("\nCalling remove(1, 'one')" );
boolean isRemoved = map.remove(1, "one");
System.out.println("Is mapping remove -" + isRemoved);
System.out.println("The map is -" + map );
System.out.println("\nCalling remove(2, 'three')" );
isRemoved = map.remove(2,"three");
System.out.println("Is mapping remove -" + isRemoved);
System.out.println("The map is -" + map );
}
}

Explanation

In the code above:

  • Line 1: We imported the WeakHashMap class.

  • Line 5: We created a WeakHashMap object with the name map.

  • Line 6 and 7: We used the put method to add two mappings ({1=one, 2=two}) to the map object.

  • Line 11: We used the remove method to remove key 1 and value one mapping. This method will check if there is an entry present for 1-one mapping. In our case, there is an entry. So, the mapping will be removed, and true is returned.

  • Line 16: We used the remove method to remove the key 2 and value three mapping. This method will check if there an entry is present for the 2-three entry. In our case, there is no entry present. So, false will be returned.

Free Resources