Difference Between IdentityHashMap, WeakHashMap, and EnumMap in Java
Last Updated :
07 Jan, 2021
The IdentityHashMap, WeakHashMap, and EnumMap all are the classes in java collection that implements the Map interface. But there are few differences exists between them.
1. IdentityHashMap: The IdentityHashMap implements the Map interface. It follows reference-equality in place of object-equality when comparing keys (and values). This class is used when the user requires the objects to be compared via reference. It is not synchronized and must be synchronized externally. The iterators in this class are fail-fast, throw ConcurrentModificationException in an attempt to modify while iterating.
Working of IdentityHashMap:
Java
// Java program to illustrate the
// working of IdentityHashmap
import java.util.*;
public class IteratingIdentityHashMap {
public static void main(String[] args)
{
// Creating an empty IdentityHashMap
IdentityHashMap<Integer, String> ihmap
= new IdentityHashMap<Integer, String>();
// Mapping string values to int keys
ihmap.put(10, "Geeks");
ihmap.put(20, "4");
ihmap.put(30, "Geeks");
ihmap.put(40, "Welcomes");
ihmap.put(50, "You");
// Displaying the size of IdentityHashMap
System.out.println("IdentityHashMap size : "
+ ihmap.size());
// Displaying the IdentityHashMap
System.out.println("Initial identity hash map: "
+ ihmap);
// Create an Iterator over the
// IdentityHashMap
Iterator<IdentityHashMap.Entry<Integer, String> >
itr = ihmap.entrySet().iterator();
// The hasNext() method is used to check if there is
// a next element The next() method is used to
// retrieve the next element
while (itr.hasNext())
{
IdentityHashMap.Entry<Integer, String> entry = itr.next();
System.out.println("Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
}
}
OutputIdentityHashMap size : 5
Initial identity hash map: {10=Geeks, 40=Welcomes, 50=You, 30=Geeks, 20=4}
Key = 10, Value = Geeks
Key = 40, Value = Welcomes
Key = 50, Value = You
Key = 30, Value = Geeks
Key = 20, Value = 4
2. WeakHashMap: WeakHashMap is the implementation of the Map interface that stores only weak keys. In WeakHashMap, we can store only weak references of its key that allows a key-value pairs to be garbage collected when its key is no longer in ordinary use. WeakHashMap is the HashTable based implementation, but it is not synchronized. It allows you to store both null key and null values.
Working of WeakHashMap:
Java
// Java program to illustrate
// the WeakHashMap
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> whmap = new WeakHashMap<Number, String>();
whmap.put(1, "geeks");
whmap.put(2, "4");
whmap.put(3, "geeks");
whmap.put(4, "welcomes");
whmap.put(5, "you");
// Displaying weak hash map
System.out.println("WeakHashMap is : " + whmap);
// Checking if "welcomes" exist
if (whmap.containsValue("welcomes"))
System.out.println("Yes welcomes exist");
// Checking if 3 exist as a key in map
if (whmap.containsKey(3))
System.out.println("Yes 3 exist");
// Creating set for key
Set keyset = whmap.keySet();
// Displaying key set
System.out.println("key Set : " + keyset);
Collection values = whmap.values();
// Displaying values of map
System.out.println("Values : " + values);
// Removing all data
whmap.clear();
// Checking whether map is empty or not
if (whmap.isEmpty())
System.out.println("Empty WeakHashMap: " + whmap);
}
}
OutputWeakHashMap is : {5=you, 4=welcomes, 3=geeks, 2=4, 1=geeks}
Yes welcomes exist
Yes 3 exist
key Set : [5, 4, 3, 2, 1]
Values : [you, welcomes, geeks, 4, geeks]
Empty WeakHashMap: {}
3. EnumMap: EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. Few important features of EnumMap are as follows:
- EnumMap class is a member of the Java Collections Framework and it is not synchronized.
- EnumMap is an ordered collection, and they are maintained in the natural order of their keys(the natural order of keys means the order on which enum constant are declared inside enum type)
- EnumMap is much faster than HashMap.
- All keys of each EnumMap instance must be keys of a same enum type.
- EnumMap doesn’t allow to insert null key if we try to insert the null key, it will throw NullPointerException.
- EnumMap is internally represented as arrays therefore it gives the better performance.
Working of EnumMap:
Java
// Java program to illustrate working
// of EnumMap
import java.util.*;
class EnumMapExample {
public enum Months {
January,
February,
March,
April;
}
public static void main(String[] args)
{
// Creating an EnumMap of the Days enum
EnumMap<Months, Integer> enumMap = new EnumMap<>(Months.class);
// Insert using put() method
enumMap.put(Months.January, 31);
enumMap.put(Months.February, 28);
enumMap.put(Months.March, 31);
enumMap.put(Months.April, 30);
// Printing size of EnumMap
System.out.println("Size of EnumMap: "
+ enumMap.size());
// Printing the EnumMap
for (Map.Entry m : enumMap.entrySet())
{
System.out.println(m.getKey() + " "
+ m.getValue());
}
}
}
OutputSize of EnumMap: 4
January 31
February 28
March 31
April 30
Difference between IdentityHashMap, WeakHashMap, and EnumMap:
PROPERTIES | IdentityHashMap | WeakHashMap | EnumMap |
---|
References | IdentityHashMap stores strong key reference. | WeakHashMap stores the weak key reference. | EnumMap stores the strong key reference. |
Search and get the values | It uses equality operator (==) to search and get the values. | It uses equals() method for that purpose. | It also uses equals() method for that purpose. |
Keys | It allows to store any type of keys. | It also allows to store any type of keys. | It allows to store only enum type keys. |
Underlined data structure | It uses the array as an underlined data structure. | It uses the HashTable as an underlined data structure. | It uses the array as an underlined data structure. |
Iterator | Iterator used in IdentityHashMap is Fail-fast. | Iterator used in WeakHashMap is Fail-fast. | Iterator used in EnumMap is weakly consistent. |
Null Values | It allows to store null values. | It allows to store null values. | It doesn't allow to store null values |
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