HashMap class

In this article, we will discuss HashMap class – one of the Map implemented classes in detail

HashMap based on hashcode of keys where keys are unique

 

HashMap:

  • HashMap is the implementation class of Map interface (i.e.; HashMap implements Map)
  • HashMap uses hash table to store key-value pairs (which is known as map entry)
  • HashMap allows only unique keys but there is no restriction on values which can be duplicated
  • At any time, HashMap contains only unique keys
  • Insertion order is NOT maintained
  • While iterating through HashMap, we will get map entries in random order (as against insertion order)
  • Allows NULL insertion for key but maximum of only one
  • Also, allows NULL insertion for values without any upper limit i.e.; we can insert null value against any unique key
  • Without generics, HashMap allows to insert any type of key and values; with generics, it is type-bounded (except, if we take both key-value as Objects within angle brackets)
  • HashMap is non-synchronized
  • Search operation is faster i.e.; searching any element from HashMap is faster, as it uses hashing to store elements
  • Present in java.util package and extends java.util.AbstractMap implements java.util.Map interface
  • Also, implements java.lang.Cloneable, java.io.Serializable marker interfaces which provides special ability to HashMap (provided by JVM at run time)

Cloneable: to create a duplicate object or to clone an object

Serializable: to transfer objects across network

27-HashMap-in-java

Source: Team BenchResources.Net

 

 

HashMap constructors:

HashMap hm = new HashMap();

  • creates an empty HashMap object of size 16 with default fill ratio of 0.75

 

HashMap hs = new HashMap(int initialCapacity);

  • creates an empty HashMap object of specified size (or initial capacity) with default fill ratio 0.75

 

HashMap hs = new HashMap(int initialCapacity, float loadFactor);

  • creates an empty HashMap object of specified size (or initial capacity) and specified fill ratio (for example 0.85)

 

HashMap hs = new HashMap(Map m);

  • creates an equivalent HashMap object for the specified map
  • it is basically used for inter-conversion between map objects

 

Fill ratio (or Load factor)

  • Fill ratio is also known as Load factor
  • This factor determines when to increase the size of HashMap automatically
  • For example, for the 1st two constructors the default load factor is 0.75 –> which means after filling 75% of original HashMap, new HashMap of bigger size will be created
  • For 3rd constructor, programmer can define load factor while creating HashMap object. If programmer defined it to be 0.95, then after filling 95% of HashMap, size of HashMap will be increased automatically
  • The value of Load factor should be in between 0 to 1.0

 

 

HashMap examples:

 

HashMapAddAndRemove.java

package in.bench.resources.java.collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapAddAndRemove {

	public static void main(String[] args) {

		// creating HashMap object of type <Integer, String>
		HashMap<Integer, String> hm = new HashMap<Integer, String>();

		// adding key-value pairs to HashMap object
		hm.put(1, "Google");
		hm.put(2, "Facebook");
		hm.put(3, "Yahoo");
		hm.put(4, "Amazon");
		hm.put(5, "Reddit");

		System.out.println("Printing all key-value pairs inside {}\n"
				+ hm + "\n");

		System.out.println("\nIterating using keySet\n");

		// Iterating key-pairs using keySet
		Set<Integer> keys = hm.keySet();
		for(Integer key : keys) {
			System.out.println(key + "  " + hm.get(key));
		}

		System.out.println("\n\nIterating using Map Entry interface\n");

		// Iterating key-pairs using Map entry
		Set set = hm.entrySet();
		Iterator iterator = set.iterator();

		while(iterator.hasNext()) {

			Map.Entry mapEntry = (Map.Entry)iterator.next();
			System.out.println(mapEntry.getKey() + "  "
					+ mapEntry.getValue());
		}

		// removing map entry at 4th position
		System.out.println("\n\nEntry removed at 4th position : "
				+ hm.remove(4));
	}
}

 

Output:

Printing all key-value pairs inside {}
{1=Google, 3=Yahoo, 2=Facebook, 5=Reddit, 4=Amazon}


Iterating using keySet

1  Google
3  Yahoo
2  Facebook
5  Reddit
4  Amazon


Iterating using Map Entry interface

1  Google
3  Yahoo
2  Facebook
5  Reddit
4  Amazon


Entry removed at 4th position : Amazon

 

 

Note: All methods of HashMap is non-synchronized but it can be easily converted into synchronized HashMap using utility method of java.util.Collections class

Map map = Collections.synchronizedMap(hm);

 

References:

https://docs.oracle.com/javase/tutorial/collections/intro/
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

 

Happy Coding !!
Happy Learning !!