In this tutorial, we will learn about Java WeakHashMap and its operations with the help of examples. We will also learn about the differences between WeakHashMap and HashMap
The WeakHashMap class of the Java collections framework provides the feature of the hash table data structure..
WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as 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.
// Java program to illustrate
// WeakHashmap
import java.util.*;
class WeakHashMapDemo
{
public static void main(String args[])throws Exception
{
WeakHashMap m = new WeakHashMap();
Demo d = new Demo();
// puts an entry into WeakHashMap
m.put(d," Hi ");
System.out.println(m);
d = null;
// garbage collector is called
System.gc();
// thread sleeps for 4 sec
Thread.sleep(4000); .
System.out.println(m);
}
}
class Demo
{
public String toString()
{
return "demo";
}
// finalize method
public void finalize()
{
System.out.println("finalize method is called");
}
}
Output:
{demo = Hi}
finalize method is called
{ }
Sr.No. | Method & Description |
---|---|
1 | void clear() Removes all mappings from this map. |
2 | boolean containsKey(Object key) Returns true if this map contains a mapping for the specified key. |
3 | boolean containsValue(Object value) Returns true if this map maps one or more keys to the specified value. |
4 | Set entrySet() Returns a collection view of the mappings contained in this map. |
5 | Object get(Object key) Returns the value to which the specified key is mapped in this weak hash map, or null if the map contains no mapping for this key. |
6 | boolean isEmpty() Returns true if this map contains no key-value mappings. |
7 | Set keySet() Returns a set view of the keys contained in this map. |
8 | Object put(Object key, Object value) Associates the specified value with the specified key in this map. |
9 | void putAll(Map m) Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map. |
10 | Object remove(Object key) Removes the mapping for this key from this map if present. |
11 | int size() Returns the number of key-value mappings in this map. |
12 | Collection values() Returns a collection view of the values contained in this map. |