Java - HashMap Vs WeakHashMap

Description

HashMap Vs WeakHashMap

Demo

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

public class Main {
  
  public static void main(String ar[]){
  
    Map hashMap= new HashMap();
    Map weakHashMap = new WeakHashMap();

    String keyHashMap = new String("keyHashMap");
    String keyWeakHashMap = new String("keyWeakHashMap");

    hashMap.put(keyHashMap, "hello");
    weakHashMap.put(keyWeakHashMap, "weak");
    System.out.println("Before: hash map value :"+hashMap.get("keyHashMap")+" and weak hash map value :"+weakHashMap.get("keyWeakHashMap"));

    keyHashMap = null;// www  .j a v a  2  s . co  m
    keyWeakHashMap = null;

    System.gc();  

    System.out.println("After: hash map value :"+hashMap.get("keyHashMap")+" and weak hash map value :"+weakHashMap.get("keyWeakHashMap"));
  }
}

Related Topic