Java WeakHashMap Example

By Arvind Rai, 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.

1. Constructors

The WeakHashMap can be created using following constructors.
1.
public WeakHashMap() 
Creates a new and empty WeakHashMap with the default initial capacity (16) and load factor (0.75).
2.
public WeakHashMap(int initialCapacity) 
Creates a new and empty 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) 
Creates a new and empty 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) 
Creates a new 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) 
Removes the mapping for the specified key.
Returns the previous value associated with the key, or null if key is not available.
2. clear
void clear() 
Removes all of the mappings of this WeakHashMap.
3. isEmpty
boolean isEmpty() 
Returns true if there is no key-value mappings.

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) 
Returns true if this map contains the specified key.
2. containsValue
boolean containsValue(Object value) 
Returns true if this map maps one or more keys to the specified 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) 
Adds the entry with specified key/value. If the key is already available, the old value is replaced.
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) 
Copies all of the mappings from the specified map to this 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); 
Output
{city=Varanasi, name=Mohit}
{country=India, city=Varanasi, name=Krishn} 

5. get and size Method

1. get
public V get(Object key) 
Returns the value for the specified key and if no mapping key is found, then returns null.
2. size
public int size() 
Returns the number of key-value mapping in this 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() 
Returns a Set view of the keys contained in this WeakHashMap.
2. values
public Collection<V> values() 
Returns a Collection view of the values contained in this 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); 
Output
[country, city, name]
[India, Varanasi, Mohit] 

7. entrySet Method

public Set<Map.Entry<K,V>> entrySet() 
Returns a Set view of the mappings contained in this map.

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());
} 
Output
country - India
city - Varanasi
name - Mohit 

8. Reference

Class WeakHashMap
POSTED BY
ARVIND RAI
ARVIND RAI











©2023 concretepage.com | Privacy Policy | Contact Us