What is the WeakHashMap.size() 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 size method of WeakHashMap returns the number of key-value mappings in the WeakHashMap object.

Syntax

public int size()

Parameter

This method doesn’t take any parameters.

Return value

This method returns the integer value representing the number of key-value mappings.

Code

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());
}
}

Explanation

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.

Free Resources