Difference Between HashMap And Identity HashMap In Java

Posted By : Avnish Pandey | 31-May-2018

As we know that HashMap class and Identity HashMap class implements Map interface, and both are having to fail fast and non-synchronized collections. In this blog, we talk about the differences between them. Some differences between HashMap class and Identity HashMap class in Java as following.

Difference between HashMap and Identity HashMap:

1. Identity HashMap class uses equality operator "==" to do the comparison for key and value in Map but HashMap uses equals method do the comparison for key and value of the object that is the main key difference.

2. Hashmap finds the bucket locations by using hashcode, but IdentityHashMap class uses "System.identityHashCode(Object)" instead of hashCode() for finding the bucket locations.

3. Identity HashMap is faster than HashMap because IdentityHashMap does not use equals(). HashMap uses equals() and hashcode() that is very expensive methods of the object.

4. One more difference between HashMap and Identity HashMap is immutability of key. If we want to store the data safely in Map than we have to use Hashmap because Identity HashMap does not require the key to be immutable because it does not use equals method and hashcode() for comparing the object.

We have also a class that is called Identity HashTable which is same as HashTable in Java but it's no longer with standard JDK and available com.sun package.

Here is an example of HashMap and Identity HashMap:

package com.base;

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

public class IdentityHashMapExample {
	public static void main(String [] args) {
		IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>();
		HashMap<String, String> hashMap = new HashMap<>();
		identityHashMap.put("1", "abc");
		identityHashMap.put(new String("1"), "xyz");
		hashMap.put("1", "abc");
		hashMap.put(new String("1"), "xyz");
		//Here the size of HashMap 1 and size of IdentityHashMap is 2
		System.out.println("Size of HashMap :: "+hashMap.size());
		System.out.println("Size of IdentityHashMap :: "+identityHashMap.size());
	}
}

Thanks,

About Author

Author Image
Avnish Pandey

Avnish has a good knowledge in core & advance Java, Spring and Hibernate Framework. He loves to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..