Java Program to Implement IdentityHashMap API
Last Updated :
18 Jul, 2024
The IdentityHashMap implements Map interface using Hashtable, using reference-equality in place of object-equality when comparing keys (and values). This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map’s general contract, which mandates the use of the equals() method when comparing objects. This class is used when the user requires the objects to be compared via reference. It belongs to java.util package. It was later added in Java 1.4
The main difference between IdentityHashMap and HashMap in java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals(obj) and hashCode() method for comparing object unlike other implementation of Map e.g. HashMap. Instead, IdentityHashMap uses the equality operator “==” to compare keys and values in Java which makes it faster compared to HashMap and suitable where you need reference equality check instead of logical equality.
Differences between IdentityHashMap and HashMap are as follows:
- The main difference between HashMap vs IdentityHashMap is that IdentityHashMap uses the equality operator “==” for comparing keys and values inside Map while HashMap uses equals(obj) method for comparing keys and values.
- Since IdentityHashMap doesn't use equals(obj), its comparatively faster than HashMap for object with expensive equals(obj) and hashCode().
- One more difference between HashMap and IdentityHashMap is the immutability of the key. One of the basic requirements of safety, when we store objects in HashMap, is keys need to be immutable, IdentityHashMap doesn't require keys to be immutable as it does not rely on equals(obj) and hashCode().
Example 1:
Java
// Java Program to illustrate IdentityHashMap by
// Differentiating between HashMap and IdentityHashMap
// Importing input output classes
import java.io.*;
// Importing HashMap, IdentityHashMap and Map classes
// from java.util package
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
// Main Class
public class GFG {
// Main driver method
public static void main (String[] args) {
// Creating objects of HashMap and IdentityHashMap objects
// Declaring objects of type String and Integer type
Map<String, Integer> hashMap = new HashMap<String, Integer>();
Map<String, Integer> identityHashMap = new IdentityHashMap<String, Integer>();
// Adding elements to objects of Maps created above
// Elements are of type key-value pairs using put() method
// Custom entries
hashMap.put("Scala", 100);
hashMap.put(new String("Scala"), 101);
hashMap.put("Groovy", 56);
hashMap.put(new String("Groovy"), 57);
identityHashMap.put("Ruby", 25);
identityHashMap.put(new String("Ruby"), 27);
identityHashMap.put("Swift", 12);
identityHashMap.put(new String("Swift"), 13);
// hashMap.size() will print 2 since
// it compares the objects logically and both the keys are same
System.out.println("Size of HashMap is : " + hashMap.size());
// identityHashMap.size() will print 4 since
// it compares the objects by reference
System.out.println("Size of IdentityHashMap is : " + identityHashMap.size());
}
}
OutputSize of HashMap is : 2
Size of IdentityHashMap is : 4
Implementation: HashMap uses hashCode() to find bucket location. IdentityHashMap doesn't use hashCode(), instead it uses System.identityHashCode(object).
Example 2:
Java
// Java Program to illustrate IdentityHashMap by
// Differentiating between HashMap and IdentityHashMap
// Importing input output classes
import java.io.*;
// Importing Map,HashMap and IdentityHashMap classes
// from java.util package
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
// Class 1
// Helper Class
class ProgrammingLanguage {
// Member variables of this class
private String language;
private Integer value;
// Constructor of this class
public ProgrammingLanguage(String language,
Integer value)
{
// this keyword refers to current object itself
this.language = language;
this.value = value;
}
// Method 1
public String getlanguage()
{
// Returning language
return language;
}
// Method 2
public Integer getValue()
{
// Returning value associated with a language
return value;
}
// Method 3
// Sets a new value for a language
public void setValue(Integer value)
{
this.value = value;
}
// Method 4
// @Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result
= prime * result
+ ((language == null) ? 0 : value.hashCode());
result
= prime * result
+ ((language == null) ? null
: language.hashCode());
return result;
}
// Method 5
// @Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProgrammingLanguage other
= (ProgrammingLanguage)obj;
if (value == null) {
if (other.value != null)
return false;
}
else if (!value.equals(other.value))
return false;
if (language == null) {
if (other.language != null)
return false;
}
else if (!language.equals(other.language))
return false;
return true;
}
}
// Class 2
// Main Class
public class GFG {
// Main driver method
public static void main(String[] args)
{
ProgrammingLanguage groovy
= new ProgrammingLanguage("Groovy", 1000);
ProgrammingLanguage scala
= new ProgrammingLanguage("Scala", 2000);
ProgrammingLanguage ruby
= new ProgrammingLanguage("Ruby", 3000);
Map<ProgrammingLanguage, Integer> languageValue
= new HashMap<>();
Map<ProgrammingLanguage, Integer>
languageValueIdentity = new IdentityHashMap<>();
// Inserting elements to object of HashMap created
// Custom entries
languageValue.put(groovy, groovy.getValue());
languageValue.put(scala, scala.getValue());
languageValue.put(ruby, ruby.getValue());
// Inserting elements to object of IdentityHashMap
// created Custom entries
languageValueIdentity.put(groovy,
groovy.getValue());
languageValueIdentity.put(scala, scala.getValue());
languageValueIdentity.put(ruby, ruby.getValue());
// Display message only
System.out.println("Before modifying keys : ");
String result = languageValue.get(groovy) != null
? "Yes"
: "No";
// Print commands to Display the result
System.out.println(
"Does Groovy language exists in HashMap? "
+ result);
result = languageValueIdentity.get(groovy) != null
? "Yes"
: "No";
System.out.println(
"Does Groovy language in IdentityHashMap? "
+ result);
// Now, modifying the value object
groovy.setValue(5000);
// Display message only
System.out.println("After modifying keys : ");
// Print commands to Display the result
result = languageValue.get(groovy) != null ? " Yes "
: " No ";
System.out.println(
"Does Groovy language exists in HashMap? "
+ result);
result = languageValueIdentity.get(groovy) != null
? " Yes "
: " No ";
System.out.println(
"Does Groovy language exists in IdentityHashMap? "
+ result);
}
}
OutputBefore modifying keys :
Does Groovy language exists in HashMap? Yes
Does Groovy language in IdentityHashMap? Yes
After modifying keys :
Does Groovy language exists in HashMap? No
Does Groovy language exists in IdentityHashMap? Yes
Output explanation:
It is clear from the output that once the programming language object is changed, which is key in both HashMap and IdentityHashMap, we are unable to retrieve an object in the case of HashMap but are able to retrieve when you use IdentityHashMap because the former uses equals() method which returns false once the value is changed and latter uses "==" operator which returns true because in both cases the object is the same in heap.
Similar Reads
Java Program to Implement ConcurrentHashMap API ConcurrentHashMap class obeys the same functional specification as HashTable and includes all the versions of methods corresponding to each method of a HashTable. A HashTable supports the full concurrency of retrievals and adjustable concurrency for updates. All the operations of ConcurrentHashMap a
6 min read
Java Program to Implement HashTable API The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. To implement Hashtable API f
4 min read
Java Program to Implement WeakHashMap API The WeakHashMap class is part of the Java Collections Framework, implementing the Map interface and extending the AbstractMap class. The Map interface helps us map key to values, while the AbstractMap class makes implementing the Map interface easier. Every key in a map must be unique and can unite
7 min read
Java Program to Implement LinkedHashMap API The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements
3 min read
Java Program to Implement LinkedHashSet API The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained, this class is used. When iterating through a HashSet, the order is unpredictable, while a LinkedHashSet lets us iterate through the element
4 min read
How to Implement a Bidirectional Map Using Two HashSets in Java? Bidirectional maps are also known as two-way maps or dual maps. These provide a convenient way to establish a relationship between keys and values in both directions. In Java, we can implement these using HashSet. So, in this article, we will see how to implement bidirectional maps in Java using two
4 min read
Traverse Through a HashMap in Java HashMap stores the data in (Key, Value) pairs, and you can access them by an index of another type. HashMap class implements Map interface which allows us to store key. hashMap is a part of the java collections framework been up since Java 1.2. It internally uses hashing technique which is pretty fa
4 min read
Java Program to Read Elements using Enumeration in Hashtable The enumeration in java is one of the predefined interfaces, whose object is used for retrieving the data from collections framework variable(like Stack, Vector, HashTable, etc.) in a forward direction only and not in the backward direction. HashTable is a class The hash table class implements a Map
3 min read
How to Implement a Custom Hash function for Keys in a HashMap in Java? In Java, HashMap is the data structure that implements the Map interface. This is used to save the data in the form of key-value pairs. In this article, we will learn how to implement a Custom Hash function for keys in a HashMap in Java. In Java, implementing the custom hash function for keys in a H
2 min read
Creating HashMap from Other Maps in Java Map interface present in java.util package represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore, it behaves a bit differently from the rest of the collection types. A map contains unique keys. There are three main types of maps in
3 min read