Hashmap vs WeakHashMap in Java

Java 8Object Oriented ProgrammingProgramming

Details about HashMap and WeakHashMap that help to differentiate them are given as follows −

HashMap in Java

A HashMap has key-value pairs i.e. keys that are associated with the values and the keys are in arbitrary order. A HashMap object that is specified as a key is not eligible for garbage collection. This means that the HashMap has dominance over the garbage collector.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.*;
class A {
   public String toString() {
      return "A ";
   }
   public void finalize() {
      System.out.println("Finalize method");
   }
}
public class Demo {
   public static void main(String args[])throws Exception {
      HashMap hMap = new HashMap();
      A obj = new A();
      hMap.put(obj, " Apple ");
      System.out.println(hMap);
      obj = null;
      System.gc();
      Thread.sleep(5000);
      System.out.println(hMap);
   }
}

The output of the above program is as follows −

Output

{A = Apple }
{A = Apple }

WeakHashMap in Java

A WeakHashMap has key-value pairs i.e. it is quite similar to a HashMap in Java. A difference is that the WeakHashMap object that is specified as a key is still eligible for garbage collection. This means that the garbage collector has dominance over the WeakHashMap.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.*;
class A {
   public String toString() {
      return "A ";
   }
   public void finalize() {
      System.out.println("Finalize method");
   }
}
public class Demo {
   public static void main(String args[])throws Exception {
      WeakHashMap whMap = new WeakHashMap();
      A obj = new A();
      whMap.put(obj, " Apple ");
      System.out.println(whMap);
      obj = null;
      System.gc();
      Thread.sleep(5000);
      System.out.println(whMap);
   }
}

The output of the above program is as follows −

Output

{A = Apple }
Finalize method
{}
raja
Updated on 30-Jul-2019 22:30:25

Advertisements