Menu
Topics Index
...
`


Collections Framework > Map Classes >
Siva Nookala - 15 Apr 2016
WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbagecollected when its key is no longer referenced outside of the WeakHashMap.

The WeakHashMap class supports four constructors.
ConstructorDescription
WeakHashMap()It constructs a new, empty WeakHashMap with the default initial capacity (16) and the default load factor (0.75).
WeakHashMap(int initialCapacity)It constructs a new, empty WeakHashMap with the given initial capacity and the default load factor, which is 0.75:.
WeakHashMap(int initialCapacity, float loadFactor)It constructs a new, empty WeakHashMap with the given initial capacity and the given load factor.
WeakHashMap(Map t)It constructs a new WeakHashMap with the same mappings as the specified Map.
WeakHashMapTest
import java.util.*;

class WeakHashMapTest
{
        public static void main(String args[])
        {    
          Map weakmap=  (Map) new WeakHashMap();
          String one=new String("one");
          String two=new String("two");
          weakmap.put(one, "Lahari");
          weakmap.put(two, "Latha");
          System.gc();
          System.out.println("Before: "+weakmap.get("one")+" "+weakmap.get("two"));
          one=null;
          two=null;
           System.gc();
          System.out.println("After: "+weakmap.get("one")+" "+weakmap.get("two"));  
        }
}
OUTPUT

Before: Lahari Latha
After: null null

DESCRIPTION

In the above example program we have taken WeakHashMap,we will put entry for the weakmapobject and then garbage collected.In the WeakHashMap object entry will be there.Later we will make reference keys one,two as null,then garbage collected and again check the entry in WeakHashMap object there will no entry, it return null values.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.