<p>In this article, the Difference between <em>HashMap</em> and <em>IdentityHashMap</em>, we will discuss IdentityHashMap and difference between IdentityHashMap and HashMap. In previous articles, we have discussed very interesting topics such as <strong><a href="https://dineshonjava.com/internal-working-of-hashmap-in-java/">How does HashMap work internally</a></strong>, and the <strong><a href="https://dineshonjava.com/difference-between-treemap-vs-hashmap/">difference between HashMap and TreeMap</a></strong>. Important points to be considered for choosing the right map implementation in the Java development. Also, discussed <strong><a href="https://dineshonjava.com/internal-working-of-treemap-in-java/">How does TreeMap work internally</a></strong>.</p>
<p><img class="aligncenter size-full wp-image-4330" src="https://dineshonjava.com/wp-content/uploads/2018/10/IdentityHashMap-vs-HashMap.png" alt="Difference between HashMap and IdentityHashMap" width="730" height="348" /></p>
<h2>IdentityHashMap in Java</h2>
<p><em>IdentityHashMap</em> implements <strong><a href="https://dineshonjava.com/map-interface-in-collection/"><em>Map</em></a></strong>, <strong><a href="https://dineshonjava.com/serialization-in-java/"><em>Serializable</em> </a></strong>and <em>Clonable</em> interfaces and extends <em>AbstractMap</em> class. We must avoid <em>IdentityHashMap</em> class for general purpose. While this class implements Map interface like other map implementation classes such as <strong><a href="https://dineshonjava.com/hashmap-class-in-collection-framework/"><em>HashMap</em></a></strong>, <strong><a href="https://dineshonjava.com/linkedhashmap-class-in-collection/"><em>LinkedHashMap</em></a></strong>, <strong><a href="https://dineshonjava.com/treemap-class-in-collection-framework/"><em>TreeMap</em></a></strong>, and <strong><a href="https://dineshonjava.com/hashtable-class-in-collection-framework/"><em>HashTable</em></a></strong>. But it intentionally violates Map&#8217;s general contract which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.</p>
<h3>Constructors</h3>
<ul>
<li><strong>IdentityHashMap():</strong> Constructs a new, empty identity hash map with a default expected maximum size.</li>
<li><strong>IdentityHashMap(int expectedMaxSize):</strong> Constructs a new, empty map with the specified expected maximum size.</li>
<li><strong>IdentityHashMap(Map m):</strong> Constructs a new identity hash map containing the key-value mappings in the specified map.</li>
</ul>
<h2>Difference between HashMap and IdentityHashMap</h2>
<p>IdentityHashMap in java is available since JDK 4, this class also implements the Map interface like HashMap and LinkedHashMap with a hash table. But the IdentityHashMap uses reference-equality in place of object-equality when comparing keys. Suppose in an IndentityHashMap, there are two keys key1 and key2, there two keys are considered equal if and only if <em>(key1==key2)</em>.</p>
<p>But in HashMap implementation, there are two keys key1 and key2, these keys are considered equal if and only if <em>(k1==null ? k2==null: k1.equals(k2)).</em>) Let&#8217;s discuss this difference using an example as the following:</p>
<h3><strong>Create a Key class</strong></h3>
<p>Here I will create a new Key class, that will be used as the key for IdentityHashMap and HashMap.</p>
<pre>package com.dineshonjava.algo.map; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class Key{ 
	 
	final int data = 112; 
	private String key; 
	 
	public Key(String key) { 
		super(); 
		this.key = key; 
	} 
	 
	@Override 
	public int hashCode() { 
		final int prime = 31; 
		int result = 1; 
		result = prime * result + data; 
		result = prime * result + ((key == null) ? 0 : (key.charAt(0)+"").hashCode()); 
		System.out.println("hashCode for key: "+ key + " = " + result); 
		System.out.println("Index "+ (result &; 15)); 
		return result; 
	} 
 
	@Override 
	public boolean equals(Object obj) { 
		System.out.println("equals for key: "); 
		if (this == obj) 
			return true; 
		if (obj == null) 
			return false; 
		if (getClass() != obj.getClass()) 
			return false; 
		Key other = (Key) obj; 
		if (data != other.data) 
			return false; 
		if (key == null) { 
			if (other.key != null) 
				return false; 
		} else if (!key.equals(other.key)) 
			return false; 
		return true; 
	} 
	 
} 
</pre>
<p>In the above Key class, the<em> hashCode()</em> method is overridden so that it returns calculated hash value. The <em>equals()</em> method is overridden so that keys are equal if key and data are equal.</p>
<p>To understand the exact difference between <em>IdentityHashMap</em> and <em>HashMap</em>, we will simply try to write a small program to check what happens when we put some equal elements in HashMap and IdentityHashMap.</p>
<h3><strong>Putting value into HashMap</strong></h3>
<p>Let&#8217;s put same values into HashMap as the following:</p>
<pre>package com.dineshonjava.algo.map; 
 
import java.util.HashMap; 
import java.util.Map; 
 
/** 
* @author Dinesh.Rajput 
* 
*/ 
public class HashMapTest { 
 
/** 
* @param args 
*/ 
public static void main(String[] args) { 
Map<;Key, String>; map = new HashMap<;>;(); 
Key key1 = new Key("Dinesh"); 
Key key2 = new Key("Dinesh"); 
Key key3 = new Key("Dinesh"); 
Key key4 = new Key("Dinesh"); 
map.put(key1 , "Dinesh"); 
map.put(key2 , "Dinesh"); 
map.put(key3 , "Dinesh"); 
map.put(key4 , "Dinesh"); 
System.out.println(map.size()); 
} 
 
} 
</pre>
<p>Note that all key objects are meaningfully equal and hence HashMap doesn’t allow duplicate keys, so it will print the size of Hashmap as 1.</p>
<p>Now let us try above program with <em>IdentityHashMap</em>.</p>
<h3>Putting the values in IdentityHashMap</h3>
<p>Let&#8217;s put same values into IdentityHashMap as the following:</p>
<pre>package com.dineshonjava.algo.map; 
 
import java.util.IdentityHashMap; 
import java.util.Map; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class IdentityHashMapTest { 
 
	/** 
	 * @param args 
	 */ 
	public static void main(String[] args) { 
		Map<;Key, String>; map = new IdentityHashMap<;>;(); 
		Key key1 = new Key("Dinesh"); 
 Key key2 = new Key("Dinesh"); 
 Key key3 = new Key("Dinesh"); 
 Key key4 = new Key("Dinesh"); 
		map.put(key1 , "Dinesh"); 
		map.put(key2 , "Dinesh"); 
 map.put(key3 , "Dinesh"); 
		map.put(key4 , "Dinesh"); 
		System.out.println(map.size()); 
	} 
 
} 
</pre>
<p>This will print 4, because, for IdentityHashMap, all keys key1, key2, key3, and key4 are not meaningfully equal. If we refer to one object using 4 references like below,</p>
<pre>Key key1 = new Key("Dinesh"); 
Key key2 = key1; 
Key key3 = key1; 
Key key4 = key1; 
</pre>
<p>then they will qualify for equality, So the program below will output 1.</p>
<pre>package com.dineshonjava.algo.map; 
 
import java.util.IdentityHashMap; 
import java.util.Map; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class IdentityHashMapTest { 
 
	/** 
	 * @param args 
	 */ 
	public static void main(String[] args) { 
		Map<;Key, String>; map = new IdentityHashMap<;>;(); 
 Key key1 = new Key("Dinesh"); 
 Key key2 = key1; 
 Key key3 = key1; 
 Key key4 = key1; 
		map.put(key1 , "Dinesh"); 
		map.put(key2 , "Dinesh"); 
 map.put(key3 , "Dinesh"); 
		map.put(key4 , "Dinesh"); 
		System.out.println(map.size()); 
	} 
 
} 
</pre>
<p>While putting elements, now, all keys key1, key2, key3, and key4 are equal. Now size will be 1.</p>
<p>Hope this article will be able to explain the Difference between <em>HashMap</em> and <em>IdentityHashMap</em>.</p>
<div align="center"><iframe style="width: 120px; height: 240px;" src="//ws-in.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&;OneJS=1&;Operation=GetAdHtml&;MarketPlace=IN&;source=ac&;ref=tf_til&;ad_type=product_link&;tracking_id=dineshonjav06-21&;marketplace=amazon&;region=IN&;placement=1787127567&;asins=1787127567&;linkId=a1e64f621b5e6128d8cb10e876eb1c48&;show_border=true&;link_opens_in_new_window=true&;price_color=333333&;title_color=0066c0&;bg_color=ffffff" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" align="center"><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span><br />
</iframe></div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/hashmap-performance-improvement-changes-in-java-8/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/what-is-new-added-features-in-java-11/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '4329'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…