Java.util.HashMap in Java

What is HashMap?

HashMap is a part of collection in Java since 1.2. It provides the basic implementation of Map interface of Java. It stores the data in (Key, Value) pairs. To access a value you must know its key, otherwise, you can’t access it. HashMap is known as HashMap because it uses a technique Hashing. Hashing is a technique of converting a large String to small String that represents same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses link list to store key-value pairs. We will know about HashSet in detail in further articles.

Definition of HashMap

public class HashMap extends AbstractMap implements
Map, Cloneable, Serializable

HashMap is kept in java.util package. As you can see in above definition of HashMap, it extends an abstract class AbstractMap which also provides an incomplete implementation of Map interface. As you can see it also implements Cloneable and Serializable interface.
K and V in above definition represents for Key and Value respectively.
HashMap don’t allow duplicate keys, but allows duplicate values. That means A single key can’t contain more than 1 value but more than 1 key can contain a single value. HashMap allows null key also but only once and multiple null values. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. It is roughly simillar to HashTable but is unsynchronized.

Internal Structure of HashMap

Internally HashMap contains an array of Node. and a node is represented as a class which contains 4 fields :

  1. int hash
  2. K key
  3. V value
  4. Node next

We can see that node is containing a reference of its own object. So it’s a linked list.
HashMap :

Node :

Time complexity of HashMap

HashMap provides constant time complexity for basic operations, get and put, if hash function is properly written and it disperses the elements properly among the buckets. Iteration over HashMap depends on the capacity of HashMap and number of key-value pairs. Basically it is directly proportional to the capacity + size. Capacity is the number of buckets in HashMap. So it is not a good idea to keep high number of buckets in HashMap initially.

Performance of HashMap

Performance of HashMap depends on 2 parameters:

  1. Initial Capacity
  2. Load Factor

As already told capacity is simply the number of buckets where and Initial Capacity is the capacity of HashMap instance when it is created. The Load Factor is a measure that when rehashing should be done. Rehashing is a process of increasing the capacity. In HashMap capacity is multiplied by 2. Load Factor is also a measure that what fraction of the HashMap is allowed to fill before rehashing. When the number of entries in HashMap increases the product of current capacity and load factor the capacity is increased that is rehashing is done. If we keep the initial capacity higher then rehashing will never be done. But by keeping it higher it increases the time complexity of iteration. So it should be choosed very cleverly to increase the performance. The expected number of values should be taken into account to set initial capacity. Most generally preffered load factor value is 0.75 which provides a good deal between time and space costs. Load factor’s value varies between 0 and 1.

Synchronized HashMap

As it is told that HashMap is unsynchronized i.e. multiple threads can access it simultaneously. If multiple threads access this class simultaneously and at least one thread manipulates it structurally then it is necessary to make it synchronized externally. It is done by synchronizing some object which enzapsulates the map. If No such object exists then it can be wrapped around Collections.synchronizedMap() to make HashMap synchronized and avoid accidental unsynchronized access. As in following example:

Map m = Collections.synchronizedMap(new HashMap(...));

Now the Map m is synchronized.

Iterators of this class are fail-fast if any structure modification is done after creation of iterator, in any way except through the iterator’s remove method. In faliure of iterator it will throw ConcurrentModificationException.

Constructors of HashMap

HashMap provides 4 constructors and access modifier of each is public:

  1. HashMap() : It is the default constructor which creates an instance of HashMap with initial capacity 16 and load factor 0.75.
  2. HashMap(int initial capacity) : It creates a HashMap instance with specified initial capacity and load factor 0.75.
  3. HashMap(int initial capacity, float loadFactor) : It creates a HashMap instance with specified initial capacity and specified load factor.
  4. HashMap(Map map) : It creates instance of HashMapwith same mappings as specified map.

Methods of HashMap: Set 1, Set 2


// Java program to illustrate 
// Java.util.HashMap
import java.util.HashMap;
import java.util.Map;

public class GFG
    public static void main(String[] args) 
        HashMap<String, Integer> map = new HashMap<>();
        map.put("vishal", 10);
        map.put("sachin", 30);
        map.put("vaibhav", 20);
        System.out.println("Size of map is:- " + map.size());
        if (map.containsKey("vishal")) 
            Integer a = map.get("vishal");
            System.out.println("value for key \"vishal\" is:- " + a);
    public static void print(Map<String, Integer> map) 
        if (map.isEmpty()) 
            System.out.println("map is empty");

output :- map is empty
Size of map is:- 3
{vaibhav=20, vishal=10, sachin=30}
value for key "vishal" is:-10
map is empty

Related Articles:

Recent articles on Java HashMap!

This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:

3 Average Difficulty : 3/5.0
Based on 16 vote(s)