Java Collection : WeakHashMap


 

Java Collection : WeakHashMap

In this tutorial, we are going to discuss one of concept (WeakHashMap ) of Collection framework.

In this tutorial, we are going to discuss one of concept (WeakHashMap ) of Collection framework.

Java Collection : WeakHashMap

In this tutorial, we are going to discuss one of concept (WeakHashMap ) of Collection framework.

WeakHashMap :

WeakHashMap class is defined in java.util package. You can say it is Hashtable based Map which implements weak keys. When its key is not in use for ordinary use then its content automatically deleted. When any key has been discarded its entry is removed from the map, you can say this class works differently than other map implementations.

WeakHashMap defines four constructors -

  • WeakHashMap()
  • WeakHashMap(int initialCapacity)
  • WeakHashMap(int initialCapacity, float loadFactor)
  • WeakHashMap(Map t)

WeakHashMap  provides many methods. We are defining here some of them -

  • containsValue(Object value) : It is of Boolean type and returns true map maps one or more keys to the given value.
  • get(Object key) : It returns the value to which the given key is mapped in the WeakHashMap. If map contains no mapping key then it returns null.
  • put(Object key, Object value) : It puts the given value with the given key in the map.
  • remove(Object key) : It removes the mapping key for the key from the map if key is presented.

Example :

package collection;

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

class WeakHashMapExample {
	public static void main(String[] args) {
		Map weakHashMap = new WeakHashMap();
		// key for strong reference
		String value = new String("key");
		weakHashMap.put(value, "Roseindia");
		// Run garbage collection to check the key value
		System.gc();
		System.out.println(weakHashMap.get("key"));
		// give value null to strong reference
		weakHashMap.remove(value);
		System.gc();
		System.out.println(weakHashMap.get("key"));
	}
}

Output :

Roseindia
null

Ads