Wednesday, November 30, 2022
HomeJavaDistinction between HashMap vs IdentityHashMap in Java? Instance

Distinction between HashMap vs IdentityHashMap in Java? Instance


The IdentityHashMap is among the lesser recognized Map implementations from JDK. Not like normal functions Map implementations like HashMap and LinkedHashMap, it is vitally particular and its inner working is sort of totally different than HashMap. The primary distinction between IdentityHashMap and HashMap in Java is that the previous makes use of the equality operator (==) as an alternative of the equals() technique to match keys. This implies you want the identical key object to retrieve the worth from IdentityHashMap, you can not retrieve values by utilizing one other key that’s logically equal to the earlier key. 
One other essential distinction between HashMap and IdentityHashMap is that IdentityHashMap would not use hashCode() technique as an alternative it makes use of System.identityHashCode() technique. 
This can be a important distinction as a result of now you need to use mutable objects as keys in Map whose hash codes are prone to change when the mapping is saved inside IdentityHashMap.

Different Map implementation which makes use of equals() and hashCode() would not work properly with mutable keys.

For instance, for those who retailer a mapping in HashMap after which went on to vary the important thing object the hashCode generated by the important thing later is not going to be the identical as earlier than. Even for those who return the identical, the equals() technique is not going to return true if you examine key objects from entry to the given key objects.

So, that is the essential distinction between IdentityHashMap and a HashMap in Java, let’s have a look at a few extra and a few code to know this idea higher.

IdentityHashMap vs HashMap in Java

As I stated, IdentityHashMap is a lesser-known class from JDK, you may by no means use this class in your venture however a great probability is that another person may need already used it. Since most programmers spend extra time studying code than writing, it is essential to know what’s IdentityHashMap in Java, what it does, the way it works, and when to make use of this class in your Java software.

When you perceive the distinction between IdentityHashMap and HashMap, you’ll robotically learn to make the very best use of this class.

Difference between HashMap vs IdentityHashMap in Java? Example

1. The at the start distinction is that IdentityHashMap internally makes use of the == operator as an alternative of equals() technique, which suggests you may retailer a String object into IdentityHashMap and later name the comprises() technique to verify if it exists within the Map, it should solely return true if each objects are identical in heap area. It is going to return false even when each objects have the identical content material, as proven beneath:

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class HashMapVsIdentityHashMap {

  public static void foremost(String[] args) {

    Map<String, Integer> idMap = new IdentityHashMap<>();
    Map<String, Integer> hashMap = new HashMap<>();

    String str = new String("Java");

    idMap.put(str, 1);
    hashMap.put(str, 1);

    boolean isExist = idMap.containsKey("Java"); // false
    boolean isPresent = hashMap.containsKey("Java"); // true

    System.out.println("Does Java exists in IdentityHashmap? : " + isExist);
    System.out.println("Does Java exists in Hashmap? : " + isPresent);

  }

}

Output:
Does Java exist in IdentityHashmap? : false
Does Java exist in Hashmap? : true

You want JDK 7 to run this program as a result of now we have used diamond operator (<>) to shorten the Generic code, although nothing stops you from being operating it on Java SE 6 when you take away the diamond operator and specify the categories on the appropriate facet of initialization as properly e.g.

as an alternative of

Map<String, Integer> idMap = new IdentityHashMap<>();

use this

Map<String, Integer> idMap = new IdentityHashMap<String, Integer>();

Utilizing Generic can also be one of many Java coding finest practices which it is best to all the time observe post-Java 5. You may see these free Java programming programs for extra of such finest practices.

2. One other important distinction between HashMap and IdentityHashMap is that later makes use of System.identityHashCode() as an alternative of hashCode() technique of key object. This implies you can even use a mutable object as a key in IdentityHashMap, which isn’t supported by HashMap in Java. 

I imply there will not be any compilation error but it surely is not going to work as anticipated such as you will be unable to retrieve the article again when you modified it state as a result of its hashCode additionally acquired modified. Let’s examine how this works in IdentityHashMap with an instance.

HashMap vs IdenityHashMap in Java

Java Program for distinction between HashMap vs IdentityHashMap

Let’s assume now we have a category known as CreditCard, which has a area known as expiry, which is nothing however a formatted date in String format. Later we modify the CreditCard object by altering its expiry and see if you’ll find it out once more from each IdentityHashMap and HashMap or not.

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class sds {

  public static void foremost(String[] args) {

    CreditCard visa = new CreditCard("VISA", "04/12/2019");
    CreditCard grasp = new CreditCard("Grasp", "04/11/2020");
    CreditCard amex = new CreditCard("American Specific", "04/10/2021");
    
    Map<CreditCard, String> cardToExpiry = new HashMap<>();
    Map<CreditCard, String> cardToExpiryIdenity = new IdentityHashMap<>();
    
    // inserting objects to HashMap
    cardToExpiry.put(visa, visa.getExpiryDate());
    cardToExpiry.put(grasp, grasp.getExpiryDate());
    cardToExpiry.put(amex, amex.getExpiryDate());
    
    // inserting objects to IdentityHashMap
    cardToExpiryIdenity.put(visa, visa.getExpiryDate());
    cardToExpiryIdenity.put(grasp, grasp.getExpiryDate());
    cardToExpiryIdenity.put(amex, amex.getExpiryDate());
    
    
    System.out.println("earlier than modifying keys");
    String outcome = cardToExpiry.get(visa) != null? "Sure" : "No";
    System.out.println("Does VISA card exists in HashMap? " + outcome);
    
    outcome = cardToExpiryIdenity.get(visa) != null? "Sure" : "No";
    System.out.println("Does VISA card exists in IdenityHashMap? " + outcome);
    
    // modifying worth object
    visa.setExpiryDate("02/11/2030");
    
    System.out.println("after modifying keys");
    outcome = cardToExpiry.get(visa) != null? "Sure" : "No";
    System.out.println("Does VISA card exists in HashMap? " + outcome);
    
    outcome = cardToExpiryIdenity.get(visa) != null? "Sure" : "No";
    System.out.println("Does VISA card exists in IdenityHashMap? " + outcome);
  }


}

class CreditCard{
  non-public String issuer;
  non-public String expiryDate;
  
  
  public CreditCard(String issuer, String expiryDate) {
    this.issuer = issuer;
    this.expiryDate = expiryDate;
  }


  public String getIssuer() {
    return issuer;
  }


  public String getExpiryDate() {
    return expiryDate;
  }
  
  public void setExpiryDate(String expiry){
    this.expiryDate = expiry;
  }


  @Override
  public int hashCode() {
    ultimate int prime = 31;
    int outcome = 1;
    outcome = prime * outcome
        + ((expiryDate == null) ? 0 : expiryDate.hashCode());
    outcome = prime * outcome + ((issuer == null) ? 0 : issuer.hashCode());
    return outcome;
  }


  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    CreditCard different = (CreditCard) obj;
    if (expiryDate == null) {
      if (different.expiryDate != null)
        return false;
    } else if (!expiryDate.equals(different.expiryDate))
      return false;
    if (issuer == null) {
      if (different.issuer != null)
        return false;
    } else if (!issuer.equals(different.issuer))
      return false;
    return true;
  }
  
  
}

Output
earlier than modifying keys
Does VISA card exists in HashMap? Sure
Does VISA card exists in IdenityHashMap? Sure
after modifying keys
Does VISA card exists in HashMap? No
Does VISA card exists in IdenityHashMap? Sure

From the output, you may see that when you modified the CreditCard object, which is vital in each HashMap and IdentityHashMap, you aren’t capable of retrieve an object within the case of HashMap however you capable of retrieve it if you use IdentityHashMap as a result of the previous makes use of an equal () technique which returns totally different worth as soon as expiry date modified and later makes use of == operator which returns true as a result of in each circumstances the article is identical in heap.

You can too see these free Java coding programs to be taught extra about IdentityHashMap class in Java.

Listed here are some extra essential factors about IdenityHashMap in Java:

  1. It makes use of id strategies i.e. equals and hashCode to retrieve values.
  2. It makes use of reference equality as an alternative of equals() technique i.e. object1 == object2 as an alternative of object1.equals(object2).
  3. For hashing, it makes use of System.identityHashCode(key) as an alternative of a key.hashCode() as utilized by different Map implementations.
  4. The java.util.IdenityHashMap class is utilized in Serialization and deep copying, the place your key’s “Class” object or interned String. 

That is all concerning the distinction between IdentityHashMap and HashMap in Java. There are uncommon circumstances the place you wish to use the IdentifyHashMap but it surely’s good to find out about it. Simply take into account that as an alternative of utilizing the equals() technique it makes use of reference equality to retailer and retrieve knowledge from Map. 

Associated Java HashMap tutorials  you might like

  • How does get() technique of HashMap work in Java? (reply)
  • What’s the distinction between HashMap and Hashtable in Java? (reply)
  • What’s the distinction between ArrayList and HashMap in Java? (reply)
  • One of the simplest ways to iterate over HashMap in Java? (reply)
  • Distinction between ArrayList and HashMap in Java? (reply)
  • Learn how to type the HashMap on keys and values in Java? (resolution)
  • 3 methods to loop over a Map in Java? (instance)
  • The distinction between HashMap and ConcurrentHashMap in Java? (reply)
  • What’s the distinction between ArrayList and HashMap? (distinction)
  • Learn how to convert Map to Listing in Java? (resolution)           
  • What’s the distinction between HashSet and HashMap in Java? (reply)
  • Distinction between ConcurrentHashMap and HashMap in Java? (reply)
  • How HashSet internally works in Java? (reply)
  • How ConcurrentHashMap internally works in Java? (reply)

Thanks for studying this text up to now. In case you like this Java
HashMap and IdentityHashMAp tutorial and Instance then please share with your folks and
colleagues. When you have any questions or suggestions, please ask in
feedback.

P. S. – If you’re new to Java and wish to be taught Java Collections framework in depth then you can even checkout these Stream and Assortment programs to begin with. It comprises finest free Java programs from Udemy and Coursera for rookies.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments