Difference betwixt HashMap vs IdentityHashMap inward Java?

The IdentityHashMap is ane of the lesser known Map implementation from JDK. Unlike full general purposes Map implementations similar HashMap too LinkedHashMap, it is rattling particular too it's internal working is quite dissimilar than HashMap. The primary departure betwixt IdentityHashMap too HashMap inwards Java is that old uses equality operator (==) instead of equals() method to compare keys. Which agency you lot take the same fundamental object to yell upward the value from IdentityHashMap, you lot cannot yell upward values past times using unopen to other fundamental which is logically equal to previous key. Another of import departure betwixt HashMap too IdentityHashMap is that IdentityHashMap doesn't utilisation hashCode() method instead it uses System.identityHashCode() method. This is a pregnant departure because straightaway you lot tin utilisation mutable objects every bit fundamental inwards Map whose hash code are probable to modify when the mapping is stored within IdentityHashMap.

Other Map implementation which uses equals() too hashCode() doesn't travel good amongst mutable keys. For example, if you lot shop a mapping inwards HashMap too thence went on to modify the fundamental object the hashCode generated past times fundamental subsequently volition non hold out the same every bit before. Even if you lot supply same, the equals() method volition non supply truthful when you lot compare fundamental object from entry to given fundamental object.

So, that's the basic departure betwixt IdentityHashMap too a HashMap inwards Java, let's run into a span of to a greater extent than too unopen to code to sympathise this concept better.




IdentityHashMap vs HashMap inwards Java

As I said, IdentityHashMap is a lesser known bird from JDK, you lot mightiness never utilisation this bird inwards your projection simply a expert jeopardy is that mortal else mightiness convey already used. Since most of the programmers pass to a greater extent than fourth dimension reading code than writing, it's of import to know what  is IdentityHashMap inwards Java, what it does, how it works, too when to utilisation this bird inwards your Java application.

Once you lot sympathise the difference betwixt IdentityHashMap too HashMap, you lot volition automatically acquire how to brand the best utilisation of this class.

1) The offset too inaugural of all departure is that IdentityHashMap internally uses == operator instead of equals() method, which agency you lot tin shop a String object into IdentityHashMap too subsequently telephone telephone the contains() method to cheque if it exists inwards the Map, it volition entirely supply truthful if both objects is same inwards heap space. It volition supply imitation fifty-fifty if both objects has same content, every bit shown below:

import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map;  public class HashMapVsIdentityHashMap {    public static void main(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 inwards IdentityHashmap? : " + isExist);     System.out.println("Does Java exists inwards Hashmap? : " + isPresent);    }  }  Output: Does Java be in IdentityHashmap? : false Does Java be in Hashmap? : true


You take JDK vii to run this computer program because nosotros convey used diamond operator (<>) to shorten the Generic code, though aught stops you lot from existence running it on Java SE half dozen ane time you lot take the diamond operator too specify the types on correct side of initialization every bit good e.g.

instead of
Map<String, Integer> idMap = new IdentityHashMap<>();
utilisation this
Map<String, Integer> idMap = new IdentityHashMap<String, Integer>();

Using Generic is besides ane of the Java coding best practices which you lot should ever follow post service Java 5. You tin see Java Coding Guidelines: 75 Recommendations for Reliable too Secure Programs for to a greater extent than of such best practices.

 Unlike full general purposes Map implementations similar  Difference betwixt HashMap vs IdentityHashMap inwards Java?



2) Another pregnant departure betwixt HashMap too IdentityHashMap is that subsequently uses System.identityHashCode() instead of hashCode() method of fundamental object. This agency you lot tin besides utilisation a mutable object every bit a fundamental inwards IdentityHashMap, which is non supported past times HashMap inwards Java. I hateful at that topographic point won't hold out whatever compilation fault simply it volition non travel every bit expected i.e. you lot volition non hold out able to yell upward object dorsum ane time you lot modified it acre because its hashCode besides got changed. Let's run into how this travel inwards IdentityHashMap amongst an example.

Let's assume nosotros convey a bird called CreditCard, which has a champaign called expiry, which is aught simply a formatted appointment inwards String format. Later nosotros modify the CreditCard object past times changing it's death too run into if you lot tin honor it out ane time again from both IdentityHashMap too HashMap or not.

Java Program to demo departure betwixt HashMap vs IdentityHashMap
import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map;  public class sds {    public static void main(String[] args) {      CreditCard visa = new CreditCard("VISA", "04/12/2019");     CreditCard original = new CreditCard("Master", "04/11/2020");     CreditCard amex = new CreditCard("American Express", "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(master, master.getExpiryDate());     cardToExpiry.put(amex, amex.getExpiryDate());          // inserting objects to IdentityHashMap     cardToExpiryIdenity.put(visa, visa.getExpiryDate());     cardToExpiryIdenity.put(master, master.getExpiryDate());     cardToExpiryIdenity.put(amex, amex.getExpiryDate());               System.out.println("before modifying keys");     String result = cardToExpiry.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA carte du jour exists inwards HashMap? " + result);          result = cardToExpiryIdenity.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA carte du jour exists inwards IdenityHashMap? " + result);          // modifying value object     visa.setExpiryDate("02/11/2030");          System.out.println("after modifying keys");     result = cardToExpiry.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA carte du jour exists inwards HashMap? " + result);          result = cardToExpiryIdenity.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA carte du jour exists inwards IdenityHashMap? " + result);   }   }  class CreditCard{   private String issuer;   private 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() {     terminal int prime number = 31;     int result = 1;     result = prime number * result         + ((expiryDate == null) ? 0 : expiryDate.hashCode());     result = prime number * result + ((issuer == null) ? 0 : issuer.hashCode());     return result;   }     @Override   public boolean equals(Object obj) {     if (this == obj)       return true;     if (obj == null)       return false;     if (getClass() != obj.getClass())       return false;     CreditCard other = (CreditCard) obj;     if (expiryDate == null) {       if (other.expiryDate != null)         return false;     } else if (!expiryDate.equals(other.expiryDate))       return false;     if (issuer == null) {       if (other.issuer != null)         return false;     } else if (!issuer.equals(other.issuer))       return false;     return true;   }       }  Output earlier modifying keys Does VISA carte du jour exists in HashMap? Yes Does VISA carte du jour exists in IdenityHashMap? Yes after modifying keys Does VISA carte du jour exists in HashMap? No Does VISA carte du jour exists in IdenityHashMap? Yes


From the output you lot tin run into that ane time you lot changed the CreditCard object, which is fundamental inwards both HashMap too IdentityHashMap, you lot are non able to yell upward object inwards instance of HashMap simply you lot able to yell upward when you lot utilisation IdentityHashMap because old uses equals() method which supply dissimilar value ane time death appointment changed too subsequently uses == operator which supply truthful because inwards both cases the object is the same inwards heap.

You tin besides read Core Java Volume 1 - Fundamentals past times Cay S. Horstmann to acquire to a greater extent than virtually IdentityHashMap bird inwards Java.

Here are unopen to to a greater extent than of import points virtually IdenityHashMap inwards Java:
  1. It uses identity methods i.e. equals too hashCode to yell upward values.
  2. It uses reference equality instead of equals() method i.e. object1 == object2 instead of object1.equals(object2).
  3. For hashing, it uses System.identityHashCode(key) instead of key.hashCode() every bit used past times other Map implementations.
  4. The java.util.IdenityHashMap bird is used inwards Serialization too deep copying, where your fundamental is "Class" object or interned String. 

 Unlike full general purposes Map implementations similar  Difference betwixt HashMap vs IdentityHashMap inwards Java?


That's all virtually the difference betwixt IdentityHashMap too HashMap inwards Java. There are rare cases where you lot desire to utilisation the IdentifyHashMap simply it's expert to know virtually it.


Related Java HashMap tutorials  you may like
  • How does get() method of HashMap travel inwards Java? (answer)
  • What is the difference betwixt HashMap too Hashtable inwards Java? (answer)
  • What is the difference betwixt ArrayList too HashMap inwards Java? (answer)
  • What is the departure betwixt HashSet too HashMap inwards Java? (answer)
  • Difference betwixt ConcurrentHashMap too HashMap inwards Java? (answer)
  • How HashSet internally industrial plant inwards Java? (answer)
  • How ConcurrentHashMap internally industrial plant inwards Java? (answer)

Further Learning
Java Fundamentals: Collections
From Collections to Streams inwards Java 8 Using Lambda Expressions
What's New inwards Java 8

Subscribe to receive free email updates:

0 Response to "Difference betwixt HashMap vs IdentityHashMap inward Java?"

Posting Komentar