HashMap and WeakHashMap Concept in java
Java.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair.
Even though the object is specified as key in hashmap, it does not have any reference and it is not
eligible for garbage collection if it is associated with HashMap i.e. HashMap dominates over Garbage Collector.
============================================================================================================================================
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
//HashMap Demonstration
package govind;
import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) throws InterruptedException {
HashMap hmap=new HashMap();
NamePrint np=new NamePrint();
hmap.put(np, "JavaTechnology");
System.out.println(hmap);
np=null;
System.gc();
Thread.sleep(4000);
System.out.println(hmap);
}
}
===========================================================================================================================================
package govind;
public class NamePrint {
public String toString()
{
return "Govind Ballabh Khan";
}
public void finalize()
{
System.out.println("Finalize Method call");
}
}
===========================================================================================================================================
o/p:---------------------------
{Govind Ballabh Khan=JavaTechnology}
{Govind Ballabh Khan=JavaTechnology}
===========================================================================================================================================
// WeakHashMap Demonstration
package govind;
import java.util.WeakHashMap;
public class WeakHashMapDemo {
public static void main(String[] args) throws InterruptedException {
WeakHashMap whm=new WeakHashMap<>();
NamePrint np=new NamePrint();
whm.put(np, "JavaTechnology");
System.out.println(whm);
np=null;
System.gc();
Thread.sleep(4000);
System.out.println(whm);
}
}
===========================================================================================================================================
package govind;
public class NamePrint {
public String toString()
{
return "Govind Ballabh Khan";
}
public void finalize()
{
System.out.println("Finalize Method call");
}
}
============================================================================================================================================
o/p:---------------------------
{Govind Ballabh Khan=JavaTechnology}
Finalize Method call
{}
No comments:
Post a Comment