DEV Community

Sonia Mathias
Sonia Mathias

Posted on

HashMap Interview Questions and Answers in Java

What is Hashmap?
Hashmaps store items in key-value pairs. It is part of the Java collection. It extends AbstractMap class and implements the map interface and is found in java.util package. The most important condition of the hashmap is that the key-value pair should be unique. If there are any duplicates found in the key then the latest value will overwrite the previous value. You can perform operations like insertion, deletion, updation, etc. in hashmaps.

In the end, we will also discuss some of the commonly asked interview questions. You can also refer to this link for more data structure-related interview questions.

For now, let’s deep dive into Hashmap in Java.

How does it work in Java?

Here are some points to remember for Hashmaps in Java:

  • It does not maintain any order.
  • It is non-synchronized.
  • It may contain one or more null values.
  • Initially, the default capacity of the Java Hashmap class is 16.

The operation of storing and retrieving the object is done at a constant time, provided that the key is known. The method to store the object is put(key, value) and the method to retrieve the object is get(key).

There are following parameters in Java Hashmap:
K: the type of keys maintained by the map
V: the type of values mapped.

Hashmap implementation in Java

The following are the constructor in Hashmap:

1. public Hashmap(): This is the default constructor which creates an instance for Hashmap with an initial capacity of 16.

Let’s look at an example for the same:
Example:

import java.io.*; 
import java.util.*; 

class Main { 

    public static void main(String args[]) 
    { 

        HashMap<Character, String> hash_1 = new HashMap<>(); //Initialization
        HashMap<Integer, String> hash_2  = new HashMap<Integer, String>(); //Initialization
        hash_1.put('A', "apple");  //put() method
        hash_1.put('B', "ball"); 
        hash_1.put('C', "cat"); 

        hash_2.put(1, "one"); 
        hash_2.put(2, "two"); 
        hash_2.put(3, "three"); 

        System.out.println("Mappings of HashMap hash_1 are : " + hash_1); 
        System.out.println("Mappings of HashMap hash_2 are : " + hash_2); 
        System.out.println(hash_1.get('A'));
        System.out.println(hash_2.get(3));
        System.out.println(hash_1.get('D'));
    } 
}
Enter fullscreen mode Exit fullscreen mode

Output:

Mappings of HashMap hm1 are : {A=apple, B=ball, C=cat}                                                                                        
Mapping of HashMap hm2 are : {1=one, 2=two, 3=three}                                                                                          
apple                                                                                                                                         
three                                                                                                                                         
null 
Enter fullscreen mode Exit fullscreen mode

2. public HashMap(int capacity): This constructor specifies the initial capacity and the load factor of 0.75 (by default). It may help in avoiding rehashing if the number of mappings is known.

Let’s look at an example:

Example:

import java.io.*; 
import java.util.*; 

class Main { 

    public static void main(String args[]) 
    { 

        HashMap<Character, String> hash_1 = new HashMap<>(7); //Initialization
        HashMap<Integer, String> hash_2  = new HashMap<Integer, String>(5); //Initialization
        hash_1.put('A', "apple");  //put() method
        hash_1.put('B', "ball"); 
        hash_1.put('C', "cat"); 

        hash_2.put(1, "one"); 
        hash_2.put(2, "two"); 
        hash_2.put(3, "three"); 

        System.out.println("Mappings of HashMap hash_1 are : " + hash_1); 
        System.out.println("Mappings of HashMap hash_2 are : " + hash_2); 
        System.out.println(hash_1.get('A'));
        System.out.println(hash_2.get(3));
        System.out.println(hash_1.get('D'));
    } 
}
Enter fullscreen mode Exit fullscreen mode

Output:

Mappings of HashMap hm1 are : {A=apple, B=ball, C=cat}                                                                                        
Mapping of HashMap hm2 are : {1=one, 2=two, 3=three}                                                                                          
apple                                                                                                                                         
three                                                                                                                                         
null
Enter fullscreen mode Exit fullscreen mode

3. public HashMap(Map<? extends K,? extends V> m):

It creates an instance using the same mapping of the specified maps.

Let’s see an example:

import java.io.*; 
import java.util.*; 

class Main { 
    public static void main(String args[]) 
    { 
        Map<Character, String> h1 = new HashMap<>(); 
        h1.put('A', "apple"); 
        h1.put('B', "ball"); 
        h1.put('C', "cat");
        h1.put('D', "dog");
        HashMap<Character, String> h2 = new HashMap<Character, String>(h1); 
        System.out.println("Mappings of HashMap h1 are : " + h1); 
        System.out.println("Mappings of HashMap h2 are : " + h2); 
    } 
}
Enter fullscreen mode Exit fullscreen mode

Output:

Mappings of HashMap h1 are : {A=apple, B=ball, C=cat, D=dog}                                                                                 
Mappings of HashMap h2 are : {A=apple, B=ball, C=cat, D=dog}
Enter fullscreen mode Exit fullscreen mode

4. public Hashmap(int initialCapacity, float loadFactor):

This constructor creates an instance with the specified initial capacity and the load factor. Let’s see an example:

import java.io.*; 
import java.util.*; 

class Main { 
    public static void main(String args[]) 
    { 
        HashMap<Character, String> h1 = new HashMap<>(3, 0.80f); 
        HashMap<Character, String> h2 = new HashMap<Character, String>(3, 0.5f); 
        h1.put('A', "Apple"); 
        h1.put('B', "Ball"); 
        h2.put('C', "Cat"); 
        h2.put('D', "Dog"); 
        System.out.println("Mappings of HashMap h1 are : " + h1); 
        System.out.println("Mapping of HashMap h2 are : " + h2); 
    } 
}
Enter fullscreen mode Exit fullscreen mode

Output:

Mappings of HashMap h1 are : {A=Apple, B=Ball}                                                                                                
Mapping of HashMap h2 are : {D=Dog, C=Cat} 
Enter fullscreen mode Exit fullscreen mode

Interview Questions in Hashmaps

1.What do you mean by load factor?

It is the measure of how much rehashing is to be done. It is initially kept higher so rehashing doesn’t take place, but this also increases the iteration time. The most common load factor value is 0.75. It varies from 0- 1.

2.Is it possible to use any custom object as a key in Hashmap?

Yes, we can use the custom object as a key in a hashmap by implementing hashcode() and equals() in the custom class. But the condition is that the hashcode should not vary once the object is inserted in the map.

3.Hashmap handles collisions in Java. Justify.

The java.util.Hashmap class in Java uses the approach of chaining to handle collisions. In chaining, if the new values with the same key are attempted to be pushed, then these values are stored in a linked list stored in a bucket of the key as a chain along with the existing value. In the worst-case scenario, it can happen that all keys might have the same hashcode, which will result in the hash table turning into a linked list. In this case, searching a value will take O(n) complexity as opposed to O(1) time due to the nature of the linked list. Hence, care has to be taken while selecting hashing algorithms.

4.What will happen if two different HashMap key objects have the same hashcode?

They will be stored in the same bucket but no next node of the linked list. And keys equals () method will be used to identify the correct key-value pair in HashMap.

5.What are things an object needs to be used as a key or value in the Hashmap?

The key and value along with its implementation should have the two functions hashcode() and equals(). The function that has the name of hashcode() is used when we insert the value of the key in any HashMap. At the same time, the function of equals() is called only when we are trying to get back the value that was already stored in the HashMap.

6.Can we use Hashmaps in the case where we need to store null values?

Yes, you can use the hashmaps to store null values without any issues. You can store one or multiple null values as per the requirement.

7.How can you handle null keys in hashmaps?

There are two separate methods for that putForNullKey(V value) and getForNullKey(). Null keys always map to index 0. The equals() and hashcode() methods are not used in the case of null keys in HashMap.

Here is how nulls are retrieved from HashMap:

private V get_null_key() {
       if (size == 0) {
            return null;
        }
        for (Entry<K,V> a = table[0]; a != null; a = a.next) {
            if (a.key == null)
                return a.value;
        }
        return null;
    }
Enter fullscreen mode Exit fullscreen mode

8.Is it possible to store multiple values under the same key using Java Hashmaps?

No, you will not be able to store duplicate keys in the hashmap. If you try to store a new value in a key already present in the hashmap, then the hashmap would simply remove the value that was earlier stored in that key and replace it with the new one.
The size of the hashmap, in this case, would not change, meaning there will be no addition of keys into the hashmap. This feature is one of the reasons we use the function keyset() to get back all the keys of a hashmap and that this function returns a set and not a collection (because in a set all the values have to be unique).

9.What is the difference between hashmap and hashtable?
HashTable is synchronized and HashMap is not. HashTable is a legacy class (part of JDK 1.0) that was promoted into collections framework by implementing Map interface later. It still has some extra features like Enumerator with it, which HashMap lacks. HashMap supports null keys (mapped to zero bucket), HashTable does not support null keys and throws NullPointerException for such cases.

10.List at least 10 methods in Java Hashmaps.

void clear() Remove all mappings from the map.
boolean isEmpty() Return true if this map contains no key-value mappings.
Object clone() Return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet() Return a collection view of the mappings contained in this map.
Set keySet() Return a set view of the keys contained in this map.
V put(Object key, Object value) It is used to insert an entry in the map.
void putAll(Map map) Insert the specified map in the map.
V putIfAbsent(K key, V value) Inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key) Delete an entry for the specified key.
boolean remove(Object key, Object value) Removes the specified values with the associated specified keys from the map.

Latest comments (1)

Collapse
 
bdcoder profile image
Bikash Jain • Edited

Nice articel, you have added lot of information here. Thanks!

For the reader: If anyone wants to learn about hascode can refer to this blog also: scaler.com/topics/hashcode-in-java/

This would definetly help some folks.