The Java WeakHashMap class is a hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed by the garbage collector, when its key is no longer in use. Following are the important points about WeakHashMap −
Both null values and the null key are supported.
Like most collection classes, this class is also not synchronized.
This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator.
Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference.
This class is a member of the Java Collections Framework.
Following is the declaration for java.util.WeakHashMap class −
public class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>
Here <K> is the type of keys maintained by this map and <V> is the type of mapped values.
Class constructors Sr.No. Constructor & Description 1WeakHashMap()
This constructor is used to create an empty WeakHashMap with the default initial capacity (16) and load factor (0.75).
2WeakHashMap(int initialCapacity)
This constructor is used to create an empty WeakHashMap with the given initial capacity and the default load factor (0.75).
3WeakHashMap(int initialCapacity, float loadFactor)
This constructor is used to create an empty WeakHashMap with the given initial capacity and the given load factor.
4WeakHashMap(Map<? extends K,? extends V> m)
This constructor is used to create a new WeakHashMap with the same mappings as the specified map.
Class methods Methods inheritedThis class inherits methods from the following classes −
The following example shows the usage of Java WeakHashMap put() method to put few values in a Map. We've created a Map object of Integer,Integer pairs. Then few entries are added using put() method and then map is printed.
package com.tutorialspoint; import java.util.WeakHashMap; public class WeakHashMapDemo { public static void main(String args[]) { // create hash map WeakHashMap<Integer,Integer> newmap = new WeakHashMap<>(); // populate hash map newmap.put(1, 1); newmap.put(2, 2); newmap.put(3, 3); System.out.println("Map elements: " + newmap); } }Output
Let us compile and run the above program, this will produce the following result.
Map elements: {3=3, 2=2, 1=1}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4