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:
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:
- Map interface
- Entry interface
- HashMap class
- LinkedHashMap class
- IdentityHashMap class
- WeakHashMap class
- SortedMap interface
- NavigableMap interface
- TreeMap class
- Hashtable class
- HashMap vs LinkedHashMap
- HashMap v/s LinkedHashMap v/s TreeMap
- HashMap v/s HashSet
- HashMap v/s Hashtable
- Properties class
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
- https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
- https://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html
Happy Coding !!
Happy Learning !!