Tuesday 25 August 2015

IdentityHashMap vs.HashMap

Introduced in JDK 1.4.

IdentityHashMap is a special implementation of Map interface which doesn't use equals() and hashCode() method for comparing object unlike other implementation of Map e.g. HashMap.
Instead IdentityHashMap use equality operator "=="  to compare keys and values which makes it faster compare to HashMap and suitable where you need reference equality check and instead of logical equality.

Like HashMap, It implements Map interface, have fail-fast Iterator and non-synchronized collections.

import java.util.IdentityHashMap;
import java.util.Map;
public class IdentityMap {
      public static void main(String args[]) {
          Map<String, String> identityMap = 
                               new IdentityHashMap<String, String>();

          identityMap.put("key""value1");
          identityMap.put(new String("key"), "value2");

          // different reference : two strings are different objects
          System.out.println("Size Map: " + identityMap.size());
          System.out.println("Map: " + identityMap);

          // same refernce key will be override
          identityMap.put("key""value3");

          System.out.println("Size Map: " + identityMap.size());
          System.out.println("Map: " + identityMap);
      }
}

Output:
Size Map: 2
Map: {key=value1, key=value2}
Size Map: 2
Map: {key=value3, key=value2}

HashMap vs IdentityHashMap


HashMap
IdentityHashMap

Equality comparison
(Main diff.)

Uses hachCode() and equals() method for keys and values comparison.

Uses equality operator "==" for comparing keys and values inside Map.


Bucket identify using

Uses hashCode() to find bucket location.

Doesn't use hashCode() instead it uses System.identityHashCode(object)

Speed

Slow, object with expensive equals() and hashCode()

Faster, Since IdentityHashMap doesn't use equals() its comparatively faster than HashMap.

Immutable key

HashMap is keys needs to be immutable (equals method compare the key internal values, so key should not modified).


No immutable key mandatory.

Usage of IdentityHashMap:
A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying.

To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed.

The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects.
For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...