WeakHashMap Class

WeakHashMap

It is exactly same as HashMap except the following differences

  • In the case of normal HashMap, an object is not eligible for GC even though it doesn’t have any references if it is associated with HashMap. That is HashMap dominates garbage collector.
  • But in the case of WeakHashMap if an object does not have any references then it’s always eligible for GC even though it is associated with WeakHashMap that is garbage collector dominates WeakHashMap.
package com.ashok.collections;

import java.util.HashMap;

public class MyHashMap {
   public static void main(String[] args) throws Exception {
      HashMap map = new HashMap();
      MyKey key = new MyKey();
      map.put(key, "Ashok");
      System.out.println(map);
      key = null;
      System.gc();
      Thread.sleep(2000);
      System.out.println(map);
   }
}

class MyKey {
   public String toString() {
      return "Key is ";
   }

   public void finalize() {
      System.out.println("finalize() method called");
   }
}

Output
{Key is =Ashok}
{Key is =Ashok}
package com.ashok.collections;

import java.util.WeakHashMap;

public class MyWeakHashMap {
   public static void main(String[] args) throws Exception {
      WeakHashMap map = new WeakHashMap();
      MyKey key = new MyKey();
      map.put(key, "Ashok");
      System.out.println(map);
      key = null;
      System.gc();
      Thread.sleep(2000);
      System.out.println(map);
   }
}

class MyKey {
   public String toString() {
      return "Key is ";
   }

   public void finalize() {
      System.out.println("finalize() method called");
   }
}

Output
{Key is :=Ashok}
finalize() method called
{}
WeakHashMap Class
Scroll to top