How to use WeakHashMap.containsKey() 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.
The containsKey() method of WeakHashMap is used to check if a value is mapped to the specified key.
Syntax
public boolean containsKey(Object key)
Parameters
The key to check for presence is passed as a parameter.
Return value
This method returns true if the key has a mapping. Otherwise, false is returned.
Code
The example below shows how to use the containsKey() method.
import java.util.WeakHashMap;class ContainsKeyExample {public static void main( String args[] ) {// create a WeakHashMap object which can have string key and integer valueWeakHashMap<String, Integer> map = new WeakHashMap<>();String key = "ten";//add a new entry to the mapmap.put(key, 10);//print the mapSystem.out.println("The map is : " + map);//check of the map contains keySystem.out.println("Checking if the key 'ten' has mapping: "+ map.containsKey(key));System.out.println("Checking if the key 'one' has mapping: "+ map.containsKey("one"));}}
Explanation
In the code above,
-
In line 1: Import the
WeakHashMapclass. -
In line 5: Create a
WeakHashMapobject with the namemap. -
In line 6: Create a
Stringobject with the namekeyand valueten. -
In line 8: Used the
putmethod to add one mapping ({ten=10}) to themapobject. -
In line 12: Use the
containsKeymethod to check if themaphas a mapping for the keyten.trueis returned as a result because the map has a mapping for the keyten. -
In line 13: Use the
containsKeymethod to check if themaphas a mapping for the keyone.falseis returned as a result because the map has a mapping for the keyone.