Table of contents
1.
Introduction
2.
WeakHashMap
3.
Features
4.
Constructors of WeakHashMap
5.
Example
5.1.
Code 1
5.2.
Code 2
5.3.
Code 3
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Mar 27, 2024

WeakHashMap

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java class provides another Map implementation that is based on weak keys. This feature was added in JDK 1.2 version and present in java.util.WeakHashMap. It simply means it is a technique in which the key not used will be collected by the garbage collector.

Also read, Duck Number in Java and  Hashcode Method in Java

WeakHashMap

The WeakHashMap is the class of Java collection framework that gives the feature of hash table data structure. Java WeakHashMap extends AbstractMap class to implement HashTable with weak keys. 

Syntax of WeakHashMap

public class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>
You can also try this code with Online Java Compiler
Run Code

Here, K is defined by the type of Keys, and The type of Values defines v.

Features

  • It helps us store data in the form of key-value pairs in java.
  • It does not allow the storage of duplicate keys.
  • It allows adding only one null key with several null values.
  • It does not maintain insertion order as it depends on HashCode.

Constructors of WeakHashMap

  • WeakHashMap(): This allows us to create a new empty WeakHashMap with an initial default capacity (16) and load factor(0.75).
  • WeakHahMap(int newCapacity): forms a new empty WeakHashMap with the user-specified capacity and a default load factor (0.75).
  • WeakHashMap(int newCapacity, float newLoadFactor): This creates a new WeakHashMap with the user-defined capacity along with the user-defined load factor.
  • WeakHashMap(Map m): This will create a whole new map with some mappings of the specified map.

Example

Code 1

import java.util.WeakHashMap;
public class Ex1 { 
	public static void main(String[] args) {
 		// Creating WeakHashMap of numbers
		WeakHashMap<String, Integer> num = new WeakHashMap<>(); 
		String name = new String("MS"); 
		Integer twoValue = 2; 
		String names = new String("MAAZ"); 
		Integer fourValue = 4; 

		// Inserting elements 
		num.put(name, twoValue);
 		num.put(names, fourValue); 
		System.out.println("WeakHashMap: " + num);

 		// Make the reference null 
		name = null; 

		// Perform garbage collection 
		System.gc(); 
		System.out.println("WeakHashMap after garbage collection: " + num);
	} 
}
You can also try this code with Online Java Compiler
Run Code

Output

WeakHashMap: {MS=2, MAAZ=4}
WeakHashMap after garbage collection: {MAAZ=4}
You can also try this code with Online Java Compiler
Run Code

We created a WeakHashMap of key-value pair of string and an integer in this code. We added those values to the map using the put function. This function takes two inputs in the form of key-value pair and then maps on the map. Here, we used the gc() function. Its function is to collect the garbage and empty the space.

Code 2

import java.util.HashMap;
import java.util.WeakHashMap;
class Ex2 {
	public static void main(String[] args) {
 		// Creating a hashmap of even numbers
		HashMap<String, Integer> evenNumbers = new HashMap<>();
		String name = new String("Saalim");
		Integer twoValue = 6;
		evenNumbers.put(name, twoValue);
		System.out.println("HashMap: " + evenNumbers);
 		// Creating a weak hash map from another hashmap
 		WeakHashMap<String, Integer> numbers = new WeakHashMap<>(evenNumbers);
		System.out.println("WeakHashMap: " + numbers);
	}
}
You can also try this code with Online Java Compiler
Run Code

Output 

HashMap: {Saalim=6}
WeakHashMap: {Saalim=6}
You can also try this code with Online Java Compiler
Run Code

In this code, we first created a HashMap, and from that, HashMap er derived a WeakHashMap. We created a HashMap of key-value pair of string and an integer. We added those values to the map using the put function. This function takes two inputs in a key-value team and then maps on the map.

Code 3

import java.util.WeakHashMap;

public class Ex3 {
    public static void main(String[] args) {
     // Creating WeakHashMap of even numbers
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();
        String one = new String("One");
        Integer oneValue = 1;
        numbers.put(one, oneValue);
        String two = new String("Two");
        Integer twoValue = 2;
        numbers.put(two, twoValue);
        System.out.println("WeakHashMap: " + numbers);
        
        // Using entrySet()
        System.out.println("Key/Value mappings: " + numbers.entrySet());
        
        // Using keySet()
        System.out.println("Keys: " + numbers.keySet());
        
        // Using values()
        System.out.println("Values: " + numbers.values());
    }
}
You can also try this code with Online Java Compiler
Run Code

Output

WeakHashMap: {Two=2, One=1}
Key/Value mappings: [Two=2, One=1]
Keys: [Two, One]
Values: [2, 1]
You can also try this code with Online Java Compiler
Run Code

Here in this code, we have created a WeakHashMap with a key-value pair of String and an Integer. We have used the put function to add those values on the map. We then used the inbuilt function entrySet to print the mapping. We also used the keySet to print the number of keys present in the map. We also used values to print the values in the map.

Also try it on java online compiler.

Frequently Asked Questions

  1. What happens when a key is removed from a WeakHashMap?
    When a value is entered, it will be removed from WeakHashMap when its key is not used. This means that there is no single reference that points to that key. When the garbage collection discards the key, the entry from the map is effectively removed from the map.
     
  2. What is meant by "it stores only weak references in Hashmap"?
    This means that only weak references allow a key-value pair to be garbage-collected, which is no longer used outside the WeakHashMap. This class helps to utilise the maximum resource of weak reference. 

Key Takeaways

In this blog, we have covered about WeakHashMap. It includes a brief introduction to WeakHashmap. We also covered what is a WeakHashMap along with its syntax. We also explained about different constructors which are used in WeakHashMap.

Recommended Readings:

 Then we took a look at a few examples where we applied WeakHashMap. If you want to learn and practice this concept, please visit our website, Guided Paths, and solve some problems asked in renowned companies' Interview Problems.

Live masterclass