Searching...
Saturday, 19 October 2013

Java WeakHashMap Example

19:02

What is WeakHashMap?

java.util.HashMap has strong key reference, even if the key is garbage collected also we can use the entry in the HashMap. But in the case of java.util.WeakHashMap key reference is very weak as its name says. Here is one simple example to store values in both HashMap and WeakHashMap and making key as null.. see the results.

Example

package com.vinod.collections;
import java.util.*;
public class WeakHashMapExample {
    public static void main(String[] args) {
        Map<String, String> hashMap = new HashMap<String, String>();
        String nameKey = new String("name");
        hashMap.put(nameKey, "Santhosh");
        System.gc();
        System.out.println("Hashmap after creation        :" + hashMap.get("name"));
        nameKey = null;
        System.gc();
        System.out.println("Hashmap after key is null     :" + hashMap.get("name"));
        Map<String, String> weakHashMap = new WeakHashMap<String, String>();
        String weaknameKey = new String("name");
        weakHashMap.put(weaknameKey, "Santhosh");
        System.gc();
        System.out.println("WeakHashMap after creation    :"
                + weakHashMap.get("name"));
        weaknameKey = null;
        System.gc();
        System.out.println("WeakHashMap after key is null :"
                + weakHashMap.get("name"));
    }
}
 

Output

Hashmap after creation        :Santhosh

Hashmap after key is null     :Santhosh

WeakHashMap after creation    :Santhosh

WeakHashMap after key is null :null

0 comments: