Java WeakHashMap Example
January 05, 2023
On this page, we will learn to use java.util.WeakHashMap
in our Java application.
1. The
WeakHashMap
is the Hash table based implementation of the Map
interface with weak keys.
2. The
WeakHashMap
has the weak keys that means the keys in the WeakHashMap
is eligible for garbage collector even if it is present in this map. Once the key is garbage collected, the entry of this key is removed from this map.
3. The
WeakHashMap
supports null values and null keys both. The performance of WeakHashMap
is similar to those of HashMap
class.
4. The
WeakHashMap
is not synchronized but can be synchronized using Collections.synchronizedMap
method.
5. The
WeakHashMap
is suitable for such object whose equal method is based on == operator check, for example, String objects. Once such a key is discarded, it can never be recreated, hence if such key is removed after some time, we cannot look up them.
6. The
WeakHashMap
can automatically remove the entries and this behavior may surprise us. Automatic removal happens because the garbage collector may discard keys at any time and then that key entry is removed from the WeakHashMap
.
7. For
WeakHashMap
, even if we synchronize it and invoke none of its mutator methods, it is possible that
the
size
method can return smaller values over time,
the
isEmpty
method can return false and then true,
the
containsKey
method can return true and later false for a given key,
the
get
method can return a value for a given key but later return null,
the
put
method can return null and the remove
method can return false for a key that previously appeared to be in the map,
the successive examinations of the key set, the value collection, and the entry set can yield successively smaller numbers of elements.
Contents
1. Constructors
TheWeakHashMap
can be created using following constructors.
1.
public WeakHashMap()
WeakHashMap
with the default initial capacity (16) and load factor (0.75).
2.
public WeakHashMap(int initialCapacity)
WeakHashMap
with the specified initial capacity and default load factor (0.75).
Throws
IllegalArgumentException
, if the initial capacity is negative.
3.
public WeakHashMap(int initialCapacity, float loadFactor)
WeakHashMap
with the specified initial capacity and load factor.
Throws
IllegalArgumentException
, if the initial capacity is negative, or if the load factor is non-positive.
4.
public WeakHashMap(Map<? extends K,? extends V> m)
WeakHashMap
with the same mappings as the specified map.
Throws
NullPointerException
if the specified map is null.
2. remove
, clear
and isEmpty
Methods
1. remove
public V remove(Object key)
Returns the previous value associated with the key, or null if key is not available.
2. clear
void clear()
WeakHashMap
.
3. isEmpty
boolean isEmpty()
Example:
WeakHashMap<String, String> map = new WeakHashMap<>(); map.put("name", "Mohit"); map.put("city", "Varanasi"); map.put("country", "India"); //remove String removedVal = map.remove("city"); System.out.println(removedVal); // Varanasi //clear map.clear(); //isEmpty boolean mappings = map.isEmpty(); System.out.println(mappings); // true
3. containsKey
and containsValue
Methods
1. containsKey
boolean containsKey(Object key)
2. containsValue
boolean containsValue(Object value)
Example:
WeakHashMap<String, String> map = new WeakHashMap<>(); map.put("name", "Mohit"); map.put("city", "Varanasi"); //containsKey boolean mapKey = map.containsKey("name"); System.out.println(mapKey); // true //containsValue boolean mapVal = map.containsValue("Varanasi"); System.out.println(mapVal); // true
4. put
and putAll
Methods
1. put
public V put(K key, V value)
Returns the previous value associated with the key, or null if there was no mapping for the key.
2. putAll
public void putAll(Map<? extends K,? extends V> m)
WeakHashMap
. If any key is already available, the old value is replaced by new value.
Example:
WeakHashMap<String, String> wmap = new WeakHashMap<>(); //put wmap.put("name", "Mohit"); wmap.put("city", "Varanasi"); System.out.println(wmap); //putAll Map<String, String> map = new HashMap<>(); wmap.put("name", "Krishn"); wmap.put("country", "India"); wmap.putAll(map); System.out.println(wmap);
{city=Varanasi, name=Mohit} {country=India, city=Varanasi, name=Krishn}
5. get
and size
Method
1. get
public V get(Object key)
2. size
public int size()
WeakHashMap
.
Example:
WeakHashMap<String, String> wmap = new WeakHashMap<>(); wmap.put("name", "Mohit"); wmap.put("city", "Varanasi"); //get String s = wmap.get("name"); // Mohit System.out.println(s); //size int n = wmap.size(); System.out.println(n); // 2
6. keySet
and values
Methods
1. keySet
public Set<K> keySet()
WeakHashMap
.
2. values
public Collection<V> values()
WeakHashMap
.
Example:
WeakHashMap<String, String> wmap = new WeakHashMap<>(); wmap.put("name", "Mohit"); wmap.put("city", "Varanasi"); wmap.put("country", "India"); //keySet Set<String> setOfKeys = wmap.keySet(); System.out.println(setOfKeys); //values Collection<String> mapValues = wmap.values(); System.out.println(mapValues);
[country, city, name] [India, Varanasi, Mohit]
7. entrySet
Method
public Set<Map.Entry<K,V>> entrySet()
Example:
WeakHashMap<String, String> wmap = new WeakHashMap<>(); wmap.put("name", "Mohit"); wmap.put("city", "Varanasi"); wmap.put("country", "India"); //entrySet Set<Map.Entry<String, String>> set = wmap.entrySet(); for(Map.Entry<String, String> m: set) { System.out.println(m.getKey() + " - " + m.getValue()); }
country - India city - Varanasi name - Mohit