Saturday, November 23, 2019

Difference Betwixt Hashmap Vs Identityhashmap Inwards Java?

The IdentityHashMap is 1 of the lesser known Map implementation from JDK. Unlike full general purposes Map implementations similar HashMap in addition to LinkedHashMap, it is rattling especial in addition to it's internal working is quite dissimilar than HashMap. The primary deviation betwixt IdentityHashMap in addition to HashMap inwards Java is that old uses equality operator (==) instead of equals() method to compare keys. Which way yous postulate the same key object to think the value from IdentityHashMap, yous cannot think values past times using about other key which is logically equal to previous key. Another of import deviation betwixt HashMap in addition to IdentityHashMap is that IdentityHashMap doesn't job hashCode() method instead it uses System.identityHashCode() method. This is a pregnant deviation because right away yous tin compass the axe job mutable objects every bit key inwards Map whose hash code are probable to alter when the mapping is stored within IdentityHashMap.

Other Map implementation which uses equals() in addition to hashCode() doesn't move good amongst mutable keys. For example, if yous shop a mapping inwards HashMap in addition to and thence went on to alter the key object the hashCode generated past times key afterward volition non move the same every bit before. Even if yous provide same, the equals() method volition non provide truthful when yous compare key object from entry to given key object.

So, that's the basic deviation betwixt IdentityHashMap in addition to a HashMap inwards Java, let's encounter a twosome of to a greater extent than in addition to about code to empathise this concept better.



IdentityHashMap vs HashMap inwards Java

As I said, IdentityHashMap is a lesser known cast from JDK, yous mightiness never job this cast inwards your projection precisely a practiced run a endangerment is that somebody 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, in addition to when to job this cast inwards your Java application.

Once yous empathise the difference betwixt IdentityHashMap in addition to HashMap, yous volition automatically larn how to brand the best job of this class.

1) The kickoff in addition to firstly deviation is that IdentityHashMap internally uses == operator instead of equals() method, which way yous tin compass the axe shop a String object into IdentityHashMap in addition to afterward telephone telephone the contains() method to banking concern friction match if it exists inwards the Map, it volition entirely provide truthful if both objects is same inwards heap space. It volition provide faux 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 postulate JDK seven to run this programme because nosotros convey used diamond operator (<>) to shorten the Generic code, though nil stops yous from existence running it on Java SE vi in 1 lawsuit yous take the diamond operator in addition to specify the types on correct side of initialization every bit good e.g.

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

Using Generic is too 1 of the Java coding best practices which yous should e'er follow ship Java 5. You tin compass the axe see Java Coding Guidelines: 75 Recommendations for Reliable in addition to 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 deviation betwixt HashMap in addition to IdentityHashMap is that afterward uses System.identityHashCode() instead of hashCode() method of key object. This way yous tin compass the axe too job a mutable object every bit a key inwards IdentityHashMap, which is non supported past times HashMap inwards Java. I hateful at that spot won't move whatever compilation mistake precisely it volition non move every bit expected i.e. yous volition non move able to think object dorsum in 1 lawsuit yous modified it solid set down because its hashCode too got changed. Let's encounter how this move inwards IdentityHashMap amongst an example.

Let's assume nosotros convey a cast called CreditCard, which has a plain called expiry, which is nil precisely a formatted appointment inwards String format. Later nosotros alter the CreditCard object past times changing it's choke in addition to encounter if yous tin compass the axe discovery it out over again from both IdentityHashMap in addition to HashMap or not.

Java Program to exhibit deviation 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 bill of fare exists inwards HashMap? " + result);          result = cardToExpiryIdenity.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA bill of fare 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 bill of fare exists inwards HashMap? " + result);          result = cardToExpiryIdenity.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA bill of fare 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() {     concluding 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 bill of fare exists in HashMap? Yes Does VISA bill of fare exists in IdenityHashMap? Yes after modifying keys Does VISA bill of fare exists in HashMap? No Does VISA bill of fare exists in IdenityHashMap? Yes


From the output yous tin compass the axe encounter that in 1 lawsuit yous changed the CreditCard object, which is key inwards both HashMap in addition to IdentityHashMap, yous are non able to think object inwards instance of HashMap precisely yous able to think when yous job IdentityHashMap because old uses equals() method which provide dissimilar value in 1 lawsuit choke appointment changed in addition to afterward uses == operator which provide truthful because inwards both cases the object is the same inwards heap.

You tin compass the axe too read Core Java Volume 1 - Fundamentals past times Cay S. Horstmann to larn to a greater extent than nearly IdentityHashMap cast inwards Java.

Here are about to a greater extent than of import points nearly IdenityHashMap inwards Java:
  1. It uses identity methods i.e. equals in addition to hashCode to think 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 cast is used inwards Serialization in addition to deep copying, where your key is "Class" object or interned String. 

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


That's all nearly the difference betwixt IdentityHashMap in addition to HashMap inwards Java. There are rare cases where yous desire to job the IdentifyHashMap precisely it's practiced to know nearly it.


Related Java HashMap tutorials  you may like
  • How does get() method of HashMap move inwards Java? (answer)
  • What is the difference betwixt HashMap in addition to Hashtable inwards Java? (answer)
  • What is the difference betwixt ArrayList in addition to HashMap inwards Java? (answer)
  • What is the deviation betwixt HashSet in addition to HashMap inwards Java? (answer)
  • Difference betwixt ConcurrentHashMap in addition to HashMap inwards Java? (answer)
  • How HashSet internally plant inwards Java? (answer)
  • How ConcurrentHashMap internally plant inwards Java? (answer)

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures in addition to Algorithms: Deep Dive Using Java

No comments:

Post a Comment