WeakHashMap
is a kind ofMap
implemented based on theHashTable
. TheWeakHashMap
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 size
method of WeakHashMap
returns the number of key-value mappings in the WeakHashMap
object.
public int size()
This method doesn’t take any parameters.
This method returns the integer value representing the number of key-value mappings.
The example below shows the use of the size
method:
import java.util.WeakHashMap;class WeakHashMapSizeExample {public static void main( String args[] ) {WeakHashMap<String, Integer> map = new WeakHashMap<>();String key1 = new String("one");String key2 = new String("two");map.put(key1, 1);map.put(key2, 2);System.out.println("WeakHashMap is : " + map);System.out.println("\nSize of the map is : " + map.size());}}
In the code above,
In line 1, we import the WeakHashMap
class.
From lines 4 to 6, we create a WeakHashMap
object and use the put
method to add two mappings({1=one, 2=two}
) to the map.
In line 8, we use the size
method to get the number of mappings present in the map. We will get 2 as a result.