Java WeakHashMap Example

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

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts