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
.
public boolean containsKey(Object key)
The key
to check for presence is passed as a parameter.
This method returns true
if the key has a mapping. Otherwise, false
is returned.
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"));}}
In the code above,
In line 1: Import the WeakHashMap
class.
In line 5: Create a WeakHashMap
object with the name map
.
In line 6: Create a String
object with the name key
and value ten
.
In line 8: Used the put
method to add one mapping ({ten=10}
) to the map
object.
In line 12: Use the containsKey
method to check if the map
has a mapping for the key ten
. true
is returned as a result because the map has a mapping for the key ten
.
In line 13: Use the containsKey
method to check if the map
has a mapping for the key one
. false
is returned as a result because the map has a mapping for the key one
.