Saturday, September 9, 2023

Top 21 Java HashMap Interview Questions and Answers

The java.util.HashMap is one of the workhorses of JDK. Along with ArrayList, it is one of the most used classes from Java's collection framework. There is hardly a real-world Java project, where I haven't seen the use of HashMap. It is an implementation of hash table data structure, and it's not a surprise that HashMap is so useful, as someone has rightly said, "if you could have just one data structure, make it a hash table". The hash table data structure allows you to search for a value in O(1) time if you have a key. In Java, several implementations of hash table data structures exist like Hashtable, ConcurrentHashMap, LinkedHashMap, etc. but HashMap is your general-purpose map.

Though, if you have a special need, you can use other hash table implementations available in JDK. For example, if you want to preserve the order of mapping, then you can consider using LinkedHashMap. If you wish to keep mappings sorted, then you can use TreeMap, which is a sorted map implementation.

Similarly, if you need a hash table implementation that is thread-safe and can be used in a concurrent application without compromising the Scalability, then consider using a ConcurrentHashMap from JDK 5.

Btw, if you are new to the Java world and JDK API in particular, I suggest you first go through an online Java course like the ones I have recommended in my list of best free core Java courses.  That will not only help you to do well on interviews but also help you to understand the fundamentals better.





Java HashMap Interview Questions

Here is my list of HashMap questions from Java Interviews. This list includes questions based on the internal implementation of HashMap, the Map API, how you use HashMap, and standard best practices while using HashMap in a Java application.


1. How does the put() method of HashMap works in Java? (answer)

The put() method of HashMap works in the principle of hashing. It is responsible for storing an object into the backend array. The hashcode() method is used in conjunction with a hash function to find the correct location for the object into the bucket. If a collision occurs, then the entry object which contains both key and value is added to a linked list, and that linked list is stored into the bucket location.


2. What is the requirement for an object to be used as a key or value in HashMap? (answer)

The key or value object must implement the equals() and hashcode() method. The hash code is used when you insert the key object into the map while equals are used when you try to retrieve a value from the map.



3. What will happen if you try to store a key that is already present in HashMap? (answer)
If you store an existing key in the HashMap, then it will override the old value with the new value, and put() will return the old value. There will not be any exception or error.


4. Can you store a null key in Java HashMap? (answer)

Yes, HashMap allows one null key, which is stored at the first location of bucket array e.g., bucket[0] = value. The HashMap doesn't call hashCode() on the null key because it will throw NullPointerException, hence when a user call the get() method with null, then the value of the first index is returned.



5. Can you store a null value inside HashMap in Java? (answer)

Yes, HashMap also allows null value; you can store as many null values as you want, as shown in the hashmap example post in this blog.



6. How does HashMap handle collisions in Java? (answer)


The java.util.HashMap uses chaining to handle collisions, which means new entries, an object which contains both key and values, are stored in a linked list along with the existing value, and then that linked list is stored in the bucket location.

In the worst case, where all key has the same hashcode, your hash table will be turned into a linked list, and searching a value will take O(n) time as opposed to O(1) time.

If you want to learn more about hash table data structure, I suggest you consult a good data structure and algorithm course like these best data structures and algorithms courses, which not only cover basic data structure like an array, linked list, binary tree, and hash table but also advanced concepts like O(n) sorting algorithms, Radix sort, Counting sort, etc.

Top 21 Java HashMap Interview Questions and Answers



7. Which data structure HashMap represents? (answer)

The HashMap is an implementation of hash table data structure, which is idle for mapping one value to other like id to name as you can search for value in O(1) time if you have the key.



8. Which data structure is used to implement HashMap in Java? (answer)

Even though HashMap represents a hash table, it is internally implemented by using an array and linked list data structure in JDK.  The array data structure is used as a bucket, while a linked list is used to store all mappings which land in the same bucket. From Java 8 onwards, the linked list is dynamically replaced by binary search tree, once a number of elements in the linked list cross a certain threshold to improve performance.



9. Can you store a duplicate key in HashMap? (answer)

No, you cannot insert duplicate keys in HashMap, it doesn't allow duplicate keys. If you try to insert an existing key with the new or same value, then it will override the old value, but the size of HashMap will not change i.e., it will remain the same. This is one of the reasons when you get all keys from the HashMap by calling keySet(). It returns a Set, not a Collection because Set doesn't allow duplicates.



10. Can you store the duplicate value in Java HashMap? (answer)

Yes, you can put duplicate values in HashMap of Java. It allows duplicate values; that's why when you retrieve all values from the Hashmap by calling the values() method, it returns a Collection and not a Set. Worth noting is that it doesn't return List because HashMap doesn't provide any ordering guarantee for key or value.

If you want to explore, you can also see these online Java Collections courses to learn more about fundamental properties of different collections in Java, like List, Set, and Map.

Java HashMap Interview Questions and Answers


11. Is HashMap thread-safe in Java? (answer)

No, HashMap is not a thread-safe in Java. You should not share a HashMap with multiple threads if one or more thread is modifying the HashMap e.g., inserting or removing a map. Though, you can easily share a read-only HashMap.


12. What will happen if you use HashMap in a multithreaded Java application? (answer)
If you use HashMap in a multithreaded environment in such a way that multiple threads structurally modify the map like add, remove or modify mapping, then the internal data structure of HashMap may get corrupt like some links may go missing, some may point to incorrect entries, and the map itself may become completely useless. Hence, it is advised not to use HashMap in the concurrent application; instead, you should use a thread-safe map e.g., ConcurrentHashMap or Hashtable.


13. What are the different ways to iterate over HashMap in Java? (answer)

Here are some of the ways to iterate over HashMap in Java:
  • by using keySet and iterator
  • by using entrySet and iterator
  • by using entrySet and enhanced for loop
  • by using keySet and get() method

You can see this article for an example of each of these ways to traverse a HashMap in Java.


14. How do you remove a mapping while iterating over HashMap in Java? (answer)
Even though HashMap provides a remove() method to remove a key and a key/value pair, you cannot use them to remove a mapping while traversing a HashMap. Instead, you need to use the Iterator's remove method to remove a mapping as shown in the following example:

Iterator itr = map.entrySet().iterator();

while(itr.hasNext()){
  Map.Entry current = itr.next();

  if(current.getKey().equals("matching"){
     itr.remove(); // this will remove the current entry.
  }
}

You can see that we have used Iterator.remove() method to remove the current entry while traversing the map. See this article to learn more about it.


15. In which order mappings are stored in HashMap? (answer)

Random order because HashMap doesn't provide any ordering guarantee for keys, values, or entries. When you iterate over a HashMap, you may get a different order every time you iterate over it.





16. Can you sort HashMap in Java? (answer)

No, you cannot sort a HashMap because, unlike List, it is not an ordered collection. Albeit, you can sort contents of HashMap by keys, values, or by entries by sorting and then storing the result into an ordered map like LinkedHashMap or a sorted map e.g., TreeMap.


17. What is the load factor in HashMap? (answer)

A load factor is a number that controls the resizing of HashMap when a number of elements in the HashMap cross the load factor as if the load factor is 0.75 and when becoming more than 75% full then resizing trigger which involves array copy.


18. How does resize happens in HashMap? (answer)

The resizing happens when the map becomes full or when the size of the map crosses the load factor. For example, if the load factor is 0.75 and then becomes more than 75% full, then resizing trigger, which involves an array copy. First, the size of the bucket is doubled, and then old entries are copied into a new bucket.


19. How many entries you can store in HashMap? What is the maximum limit? (answer)
There is no maximum limit for HashMap, you can store as many entries as you want because when you run out of the bucket, entries will be added to a linked list which can support an infinite number of entries, of course until you exhaust all the memory you have.

Btw, the size() method of HashMap return an int, which has a limit, once a number of entries cross the limit, size() will overflow, and if your program relies on that, then it will break.

This issue has been addressed in JDK 8 by introducing a new method called mappingCount(), which returns a long value. So, you should use mappingCount() for large maps. See Java SE 8 for Really Impatient to learn more about new methods introduced in existing interfaces in JDK 8.

Top 10 Java HashMap Interview Questions and Answers



21. What is the difference between the capacity and size of HashMap in Java? (answer)

The capacity denotes how many entries HashMap can store, and size denotes how many mappings or key/value pair is currently present.


21. What will happen if two different keys of HashMap return the same hashcode()? (answer)
If two keys of HashMap return the same hash code, then they will end up in the same bucket; hence collision will occur. They will be stored in a linked list together.


That's all about some of the important Java HashMap interview questions. I have tried to answer them as well, but if you disagree with an answer, then feel free to comment. Since HashMap is a very important class in Java and equally important from the Java interview point of view, it pays to understand this class and its implementation in deep.


Other Java Interview Questions list you may want to check
  • 50 Java Programs from Coding Interviews (list)
  • 19 Java Overloading and Overriding Interview Questions (list)
  • 15 Java NIO and Networking Interview Questions with Answers (see here)
  • 21 Java ArrayList Interview Questions with Answers (list)
  • 20+ String Coding Problems from Interviews (questions)
  • 21 Java Final modifier Interview Questions (list)
  • 21 String Algorithms Questions from Interviews (questions)
  • 20+ binary tree Coding problems from Interviews (questions)
  • 21 Java Inheritance Interview Questions with Answers (list)
  • 75 Coding Interview Questions for Programmers (questions
  • 10 Date, Time, and Calendar based Interview Questions with Answers (list)
  • 5 main() method interview questions (list)
  • 15 SQL and UNIX questions from Java Interviews (list)
  • 22 array concept interview questions from Java (list)
  • 25 Software Design Interview Questions for programmers (questions)
  • 15 Java Enum based Interview Questions (list)
  • 50+ Data Structure and Algorithms Interview Questions (questions)

These questions will not only help you to understand HashMap better but also encourage you to find out more about HashMap, its Java implementation, and hash table data structure in general. If you have any other HashMap based Java questions, which were asked to you in an interview, feel free to share with us.

P. S. - If you are preparing for Java Interviews and looking for some interesting questions for practice, then you can also check out these Java Interview online courses, which contains more than 200+ real-world questions from Java interviews and their explanation.

15 comments:

  1. Perfect explanation . The best line is "This is one of the reason when you get all keys from the HashMap by calling keySet() it returns a Set, not a Collection because Set doesn't allow duplicates."

    ReplyDelete
    Replies
    1. Thank you Sachindra, glad that you like my explanation.

      Delete
  2. we nicely compiled question and answers

    ReplyDelete
  3. Hah, I missed mappingCount() method :) Many thanks for article, worth of reading carefuly!

    ReplyDelete
  4. mappingCount() method is there in HashMap()?

    ReplyDelete
  5. actually answers are outdates. nothing about tree inside of bucket also, linked list would not work propertly after int_max elements and so on.

    ReplyDelete
  6. plz any body can explain Q.19 i am not getting properly getting confused

    ReplyDelete
    Replies
    1. Hello @Unknown, it says that maximum number of entries you can store in Hashmap is Integer.MAX because after that even though you can store, the size will be returned wrong as integer will overflow and return negative values. Does this help?

      Delete
  7. Very good explanation. Visited java67 first time. It seems now will be regular visitor.
    Thanks a lot!

    ReplyDelete
    Replies
    1. Thank you @Unknown, glad that you find explanations and questions useful.

      Delete
  8. Hi, I couldn`t find mappingCount() in JAVA8

    ReplyDelete
  9. In question no 3 that will return new value man....

    If you store an existing key in the HashMap, then it will override the old value with the new value and put() will return the new value not old value.

    ReplyDelete
    Replies
    1. That is incorrect. The put() method will return the old value, or null if the key did not exist. The answer is correct.

      Delete
  10. Is there a way to define the load factor for the linked list in the Hashmap??

    ReplyDelete
    Replies
    1. Hello Anonymous, as much I know, While you can't directly control the load factor for the linked list within a bucket, you can influence it indirectly by adjusting the overall load factor of the HashMap. This can be done when you initialize the HashMap by specifying the initial capacity and load factor in the constructor

      HashMap map = new HashMap<>(initialCapacity, loadFactor);

      By setting an appropriate load factor, you can control how often the HashMap resizes, impacting the likelihood of encountering long linked lists in individual buckets.

      Just keep in mind that tweaking the load factor involves a trade-off between memory usage and performance, so it's essential to choose values based on the specific requirements and characteristics of your application.

      Delete

Feel free to comment, ask questions if you have any doubt.