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
31-WeakHashMap-in-java

Source: Team BenchResources.Net

4. WeakHashMap examples:

WeakHashMapExample.java

package in.bench.resources.java.collection;

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.gc();

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

class TempIdClass {

	Integer i;

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

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

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

Output:

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

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - SortedMap interface
Java - IdentityHashMap class with example