Last Updated: 22 January, 2023
WeakHashMap is almost similar to the HashMap class in Java. The major difference is that an entry in a WeakHashMap will automatically be removed by the garbage collector when its key is no longer in ordinary use.
There are many differences between the HashMap and WeakHashMap that are given below.
The HashMap class was introduced in the Java 1.2 version and is available in the java.util package. HashMap is a child class of the AbstractMap class, and it implements the Map interface as well as the Cloneable and Serializable interfaces.
HashMap is used to store the data in the form of key-value pairs, where keys must be unique and values may be duplicated. HashMap accepts only one null key and multiple null values.
Java HashMap Class Declaration
Here, K is the key Object type and V is the value Object type.
Java HashMap important features:
WeakHashMap is a child class of AbstractMap and implements the Map interface in Java. It was introduced in the JDK 1.2 version and is available in the java.util package, which stores only weak references to its keys.
The keys entered into a WeakHashMap are held using weak references. This allows the garbage collector to collect the keys if there are no other strong references to those keys elsewhere in the application.
Java WeakHashMap Class Declaration
Here, K is the key Object type and V is the value Object type.
Java WeakHashMap important features:
HashMap | WeakHashMap |
---|---|
The stored entry object is not eligible for garbage collection. | An entry in a WeakHashMap will be automatically removed when its key loses all strong and soft references. |
HashMap holds strong references to its key objects. | Weak references to keys are stored in the case of a WeakHashMap. |
The size() method will always return the same value unless we explicitly add or remove entries. | The size() method may return a smaller value as a few entries might be automatically removed by the GC. |
HashMap implements a Serializable interface. | WeakHashMap does not implement the Serializable interface. |
The Cloneable interface is implemented by the HashMap, and its clone() method returns a shallow copy of the HashMap. | It does not implement a clonable interface. |
Output
Iterating Hashmap and printing Key and Value
in - India
en - England
us - United State
ca - Canada
Output
WeakHashMap Data Before calling System.gc()
100 => 11, Ganesh, Sales
200 => 22, Ramesh, Operation
WeakHashMap Data After calling System.gc()
200 => 22, Ramesh, Operation
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com