What is the WeakHashMap.remove(key,value) method in Java?
WeakHashMapis a kind ofMapimplemented and based on theHashTable. TheWeakHashMaponly 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
WeakHashMapclass. -
Line 5: We created a
WeakHashMapobject with the namemap. -
Line 6 and 7: We used the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
Line 11: We used the
removemethod to remove key1and valueonemapping. This method will check if there is an entry present for1-onemapping. In our case, there is an entry. So, the mapping will be removed, andtrueis returned. -
Line 16: We used the
removemethod to remove the key 2 and valuethreemapping. This method will check if there an entry is present for the2-threeentry. In our case, there is no entry present. So,falsewill be returned.