WeakHashMap Class in Java - GeeksforGeeks

24 Jan, 2022
WeakHashMap is an implementation of the Map interface. WeakHashMap is almost the same as HashMap except in the case of WeakHashMap if the object is specified as the key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.
WeakHashMap is the Hash table-based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.
A few important features of a WeakHashMap Class are:
Both null values and null keys are supported in WeakHashMap.
It is not synchronized.
This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator.
1. WeakHashMap(): This constructor is used to create an empty WeakHashMap with the default initial capacity-(16) and load factor (0.75). 
2. WeakHashMap(int initialCapacity): This constructor is used to create an empty WeakHashMap with the given initial capacity and the default load factor (0.75). 
3. WeakHashMap(int initialCapacity, float loadFactor): This constructor is used to create an empty WeakHashMap with the given initial capacity and the given load factor. 
4. WeakHashMap(Map m): This constructor is used to create a new WeakHashMap with the same mappings as the specified map.
Example 1:
Java
// Java Program to Illustrate WeakHashMap class// Via close(), containsValue(), containsKey()// and isEmpty() method  // Importing required classesimport java.util.Map;import java.util.WeakHashMap;  // Main class// WeakHashMapdemoclass GFG {      // Main driver method    public static void main(String[] arg)    {          // Creating an empty WeakHashMap        // of Number and string type        Map<Number, String> weak            = new WeakHashMap<Number, String>();          // Inserting custom elements        // using put() method        weak.put(1, "geeks");        weak.put(2, "for");        weak.put(3, "geeks");          // Printing and alongside checking weak map        System.out.println("our weak map: " + weak);          // Checking if "for" exist        if (weak.containsValue("for"))            System.out.println("for exist");          // Checking if 1 exist as a key in Map        if (weak.containsKey(1))            System.out.println("1 exist");          // Removing all data        // using clear() method        weak.clear();          // Checking whether the Map is empty or not        // using isEmpty() method        if (weak.isEmpty())              // Display message for better readability            System.out.println("empty map: " + weak);    }}
our weak map: {3=geeks, 2=for, 1=geeks}
for exist
1 exist
empty map: {}
 Example 2:
Java
// Java Program to Illustrate WeakHashMap class// Via entrySet(), keySet() and Values() Method  // Importing required classesimport java.util.Collection;import java.util.Map;import java.util.Set;import java.util.WeakHashMap;  // Main class// WeakHashMapdemoclass GFG {      // Main driver method    public static void main(String[] arg)    {          // Creating an empty WeakHashMap        // of number and string type        Map<Number, String> weak            = new WeakHashMap<Number, String>();          // Inserting elements        // using put() method        weak.put(1, "geeks");        weak.put(2, "for");        weak.put(3, "geeks");          // Creating object of Set interface        Set set1 = weak.entrySet();          // Checking above Set        System.out.println(set1);          // Creating set for key        Set keySet = weak.keySet();          // Checking keySet        System.out.println("key set: " + keySet);          Collection value = weak.values();          // Checking values of map and printing them        System.out.println("values: " + value);    }}
[3=geeks, 2=for, 1=geeks]
key set: [3, 2, 1]
values: [geeks, for, geeks]
Example 3:
Java
// Java code remove(), putAll()// get() and size() method  import java.util.Collection;import java.util.Map;import java.util.Set;import java.util.WeakHashMap;  class WeakHashMapdemo {    public static void main(String[] arg)    {        Map<Number, String> weak            = new WeakHashMap<Number, String>();        weak.put(1, "geeks");        weak.put(2, "for");        weak.put(3, "geeks");          Map<Number, String> weak1            = new WeakHashMap<Number, String>();        weak1.putAll(weak);          // Getting value of key 2        System.out.println(weak1.get(2));          // Printing the size of map        // using size() method        System.out.println("Size of map is: "                           + weak1.size());          // Removing second element        // using standard remove() method        weak1.remove(2);          // Printing the size after removing key and value        // pair        System.out.println("Size after removing: "                           + weak1.size());    }}
for
Size of map is: 3
Size after removing: 2
This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
simranarora5sos
nishkarshgandhi
Java - util package
Java-HashMap
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Multithreading in Java
Collections in Java
Queue Interface In Java