WeakHashMap Class in Java
Last Updated :
24 Jan, 2022
WeakHashMap is an implementation of the Map interface. WeakHashMap is almost the same as HashMap except in the case of WeakHashMap if the object is specified as the key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.
WeakHashMap is the Hash table-based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.
A few important features of a WeakHashMap Class are:
- Both null values and null keys are supported in WeakHashMap.
- It is not synchronized.
- This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator.
Constructors in WeakHashMap
1. WeakHashMap(): This constructor is used to create an empty WeakHashMap with the default initial capacity-(16) and load factor (0.75).
2. WeakHashMap(int initialCapacity): This constructor is used to create an empty WeakHashMap with the given initial capacity and the default load factor (0.75).
3. WeakHashMap(int initialCapacity, float loadFactor): This constructor is used to create an empty WeakHashMap with the given initial capacity and the given load factor.
4. WeakHashMap(Map m): This constructor is used to create a new WeakHashMap with the same mappings as the specified map.
Methods in WeakHashMap
Method | Action Performed |
---|
clear() | Removes all of the mappings from this map. The map will be empty after this call returns. |
containsValue(Object value) | Returns true if this map maps one or more keys to the specified value. |
containsKey(Object key) | Returns true if this map contains a mapping for the specified key. |
entrySet() | Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. |
get(Object key) | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
isEmpty() | Returns true if this map contains no key-value mappings. This result is a snapshot, and may not reflect unprocessed entries that will be removed before next attempted access because they are no longer referenced. |
keySet() | Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. |
put(K key, V value) | Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced. |
putAll(Map m) | Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map. |
remove(Object key) | Removes the mapping for a key from this weak hash map if it is present. More formally, if this map contains a mapping from key k to value v such that (key==null ? k==null: key.equals(k)), that mapping is removed. |
size() | Returns the number of key-value mappings in this map. This result is a snapshot, and may not reflect unprocessed entries that will be removed before the next attempted access because they are no longer referenced. |
values() | Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations. |
Example 1:
Java
// Java Program to Illustrate WeakHashMap class
// Via close(), containsValue(), containsKey()
// and isEmpty() method
// Importing required classes
import java.util.Map;
import java.util.WeakHashMap;
// Main class
// WeakHashMapdemo
class GFG {
// Main driver method
public static void main(String[] arg)
{
// Creating an empty WeakHashMap
// of Number and string type
Map<Number, String> weak
= new WeakHashMap<Number, String>();
// Inserting custom elements
// using put() method
weak.put(1, "geeks");
weak.put(2, "for");
weak.put(3, "geeks");
// Printing and alongside checking weak map
System.out.println("our weak map: " + weak);
// Checking if "for" exist
if (weak.containsValue("for"))
System.out.println("for exist");
// Checking if 1 exist as a key in Map
if (weak.containsKey(1))
System.out.println("1 exist");
// Removing all data
// using clear() method
weak.clear();
// Checking whether the Map is empty or not
// using isEmpty() method
if (weak.isEmpty())
// Display message for better readability
System.out.println("empty map: " + weak);
}
}
Outputour weak map: {3=geeks, 2=for, 1=geeks}
for exist
1 exist
empty map: {}
Example 2:
Java
// Java Program to Illustrate WeakHashMap class
// Via entrySet(), keySet() and Values() Method
// Importing required classes
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
// Main class
// WeakHashMapdemo
class GFG {
// Main driver method
public static void main(String[] arg)
{
// Creating an empty WeakHashMap
// of number and string type
Map<Number, String> weak
= new WeakHashMap<Number, String>();
// Inserting elements
// using put() method
weak.put(1, "geeks");
weak.put(2, "for");
weak.put(3, "geeks");
// Creating object of Set interface
Set set1 = weak.entrySet();
// Checking above Set
System.out.println(set1);
// Creating set for key
Set keySet = weak.keySet();
// Checking keySet
System.out.println("key set: " + keySet);
Collection value = weak.values();
// Checking values of map and printing them
System.out.println("values: " + value);
}
}
Output[3=geeks, 2=for, 1=geeks]
key set: [3, 2, 1]
values: [geeks, for, geeks]
Example 3:
Java
// Java code remove(), putAll()
// get() and size() method
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
class WeakHashMapdemo {
public static void main(String[] arg)
{
Map<Number, String> weak
= new WeakHashMap<Number, String>();
weak.put(1, "geeks");
weak.put(2, "for");
weak.put(3, "geeks");
Map<Number, String> weak1
= new WeakHashMap<Number, String>();
weak1.putAll(weak);
// Getting value of key 2
System.out.println(weak1.get(2));
// Printing the size of map
// using size() method
System.out.println("Size of map is: "
+ weak1.size());
// Removing second element
// using standard remove() method
weak1.remove(2);
// Printing the size after removing key and value
// pair
System.out.println("Size after removing: "
+ weak1.size());
}
}
Outputfor
Size of map is: 3
Size after removing: 2
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read