HashMap and HashCode

jdk hashmap hashCode

Ads

Tutorials   

HashMap and HashCode

The HashMap is a class which is used to perform some basic operations such as inserting, deleting, and locating elements in a Map . The  java.util.HashMap class is implemented with and roughly equivalent to a Hashtable  except that it is unsynchronized and permits null. It works with the Iterators requires a well-defined implementation of the method hashCode( ).

HashCode is a method that returns an integer to confirm whether two objects are equal. Such objects are mainly HashMaps and HashSets. The objects are only equal if if their hashCode methods return equal integer values.

Given below example will give you a clear idea how to use HashCode :

package simpleCoreJava;

import java.util.Map;
import java.util.HashMap;
import java.util.TreeMap;

public class MapHashCode {
public static void main(String args[]) {
Map mp1 = new HashMap();
mp1.put(1, "A");
mp1.put(2, "B");
mp1.put(3, "C");
mp1.put(4, "D");
System.out.println("Mapping1 = " + mp1);
System.out.println("Size of map1 = " + mp1.size());
Map mp2 = new TreeMap();
mp2.put(1, "A");
mp2.put(2, "B");
mp2.put(3, "C");
mp2.put(4, "D");
System.out.println("Mapping2 = " + mp2);
System.out.println("Size of map2 = " + mp2.size());
boolean bol = mp1.equals(mp2);
System.out.println("Is the elements of map1 and map2 are equal : "
+ bol);
System.out.println("Hash code of map1 = " + mp1.hashCode());
System.out.println("Hash code of map2 = " + mp2.hashCode());
Map mp3 = new HashMap();
mp3.put(1, "E");
mp3.put(2, "F");
mp3.put(3, "G");
mp3.put(4, "H");
System.out.println("Mapping3 = " + mp3);
System.out.println("Size of map3 = " + mp3.size());
System.out.println("Mapping1 = " + mp1);
boolean bol1 = mp1.equals(mp3);
System.out.println("Is the elements of map1 and map3 are equal : "
+ bol1);
System.out.println("Hash code of map1 = " + mp1.hashCode());
System.out.println("Hash code of map3 = " + mp3.hashCode());
System.out.println("Mapping2 = " + mp2);
System.out.println("Mapping3 = " + mp3);
boolean bol2 = mp2.equals(mp3);
System.out.println("Is the elements of map2 and map3 are equal : "
+ bol2);
System.out.println("Hash code of map2 = " + mp2.hashCode());
System.out.println("Hash code of map3 = " + mp3.hashCode());
}
}

Output

Mapping1 = {1=A, 2=B, 3=C, 4=D}
Size of map1 = 4
Mapping2 = {1=A, 2=B, 3=C, 4=D}
Size of map2 = 4
Is the elements of map1 and map2 are equal : true
Hash code of map1 = 256
Hash code of map2 = 256
Mapping3 = {1=E, 2=F, 3=G, 4=H}
Size of map3 = 4
Mapping1 = {1=A, 2=B, 3=C, 4=D}
Is the elements of map1 and map3 are equal : false                  
Hash code of map1 = 256
Hash code of map3 = 280
Mapping2 = {1=A, 2=B, 3=C, 4=D}
Mapping3 = {1=E, 2=F, 3=G, 4=H}
Is the elements of map2 and map3 are equal : false
Hash code of map2 = 256
Hash code of map3 = 280