Java – WeakHashMap class with example

In this article, we will discuss WeakHashMap class – one of the Map implemented classes in detail

1. Key points about WeakHashMap:

  • WeakHashMap is exactly same as that of HashMap with few differences

2. HashMap:

  • If objects don’t have any reference outside of HashMap, even then objects aren’t eligible for Garbage Collection
  • HashMap has precedence over Garbage Collector

3. WeakHashMap:

  • If objects don’t have any reference outside of WeakHashMap, still JVM executes Garbage collection
  • Garbage collector has precedence over objects inside WeakHashMap
  • Kind of stores only weak references

Source: Team BenchResources.Net

4. WeakHashMap examples:


import java.util.WeakHashMap;

public class WeakHashMapExample {

	public static void main(String[] args) {

		// creating WeakHashMap object of type <Integer, String>
		WeakHashMap<TempIdClass, String> whm =
				new WeakHashMap<TempIdClass, String>();

		// creating TempIdClass objects
		TempIdClass temp1 = new TempIdClass(1);
		TempIdClass temp2 = new TempIdClass(2);

		// adding key-value pairs to WeakHashMap object
		whm.put(temp1, "Google");
		whm.put(temp2, "Facebook");

		// deliberately making NULL to test
		temp1 = null;
		temp2 = null;

		// garbage collector

		System.out.println("Printing WeakHashMap contents : " + whm);

class TempIdClass {

	Integer i;

	public TempIdClass(Integer i) {
		this.i = i;

	public String toString() {
		return "TempIdClass [i=" + i + "]";

	protected void finalize() throws Throwable {
		System.out.println("finalize method invoked for "
				+ i + " TempIdClass object");


finalize method invoked for 1 TempIdClass object
finalize method invoked for 2 TempIdClass object
Printing WeakHashMap contents : {}

Related Articles:


Happy Coding !!
Happy Learning !!

Java - SortedMap interface
Java - IdentityHashMap class with example