Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Hashmap vs WeakHashMap in Java
Details about HashMap and WeakHashMap that help to differentiate them are given as follows −
HashMap in Java
A HashMap has key-value pairs i.e. keys that are associated with the values and the keys are in arbitrary order. A HashMap object that is specified as a key is not eligible for garbage collection. This means that the HashMap has dominance over the garbage collector.
A program that demonstrates this is given as follows −
Example
import java.util.*;
class A {
public String toString() {
return "A ";
}
public void finalize() {
System.out.println("Finalize method");
}
}
public class Demo {
public static void main(String args[])throws Exception {
HashMap hMap = new HashMap();
A obj = new A();
hMap.put(obj, " Apple ");
System.out.println(hMap);
obj = null;
System.gc();
Thread.sleep(5000);
System.out.println(hMap);
}
}
The output of the above program is as follows −
Output
{A = Apple }
{A = Apple }
WeakHashMap in Java
A WeakHashMap has key-value pairs i.e. it is quite similar to a HashMap in Java. A difference is that the WeakHashMap object that is specified as a key is still eligible for garbage collection. This means that the garbage collector has dominance over the WeakHashMap.
A program that demonstrates this is given as follows −
Example
import java.util.*;
class A {
public String toString() {
return "A ";
}
public void finalize() {
System.out.println("Finalize method");
}
}
public class Demo {
public static void main(String args[])throws Exception {
WeakHashMap whMap = new WeakHashMap();
A obj = new A();
whMap.put(obj, " Apple ");
System.out.println(whMap);
obj = null;
System.gc();
Thread.sleep(5000);
System.out.println(whMap);
}
}
The output of the above program is as follows −
Output
{A = Apple }
Finalize method
{}