Wednesday, May 10, 2023

40 Java HashMap Interview Questions and Answers for 2 to 3 Years Experienced

Hello guys, HashMap and ArrayList is two of the most useful classes from JDK and every Java programmer should be familiar with them. Because of their usefulness, they are also very popular on Java interviews. You will always find a couple of questions on HashMap, ArrayList and its close cousins like Hashtable and ConcurrentHashMap on various Java interviews, ranging from freshers to experienced, junior to senior programmers, and telephonic to face-to-face interviews. To help my readers to better prepare for Java interviews, I have shared some of the essential ArrayList interview questions in my last article and today I am going to share  frequently asked questions on Java HashMap. 

These questions are collected from various sources and they have been asked into various Java interviews, you might have seen many of them already. What makes them still useful is the fact that a good knowledge of HashMap like How HashMap works and how to use it are essential for any Java developer. It is one of the key data structure and you will always find its usage in Java applications, mostly as cache to store objects.

In this list, I have shared almost 40 popular Java Interview questions, which are based upon how HashMap are implemented, how you use them, difference between HashMap and other map implementations from Java Collection framework like LinkedHashMap, TreeMap or EnumMap and some of the new methods added on Java 8. The list also contains some questions to check fundamentals of HashMap like hashing, hash collisions and how they are resolved. 




40 HashMap and Hashtable Interview Questions Answers in Java 

Here is my collection of 40 HashMap based Java interview questions. You should go through this list before appearing for any Java interviews e.g. telephonic round or face-to-face round. I have purposefully kept the answer short and to-the-point so that you don't need to spend too much time. 

I have also included links for more curious developers because I have already discussed many of these questions in detailed here. You can check them if you have more time or you want to learn more about those concepts. 

1. What is an HashMap in Java? (answer)
An HashMap is a Java implementation of popular data structure hash table, which allows you to store key value pairs e.g. books and their prices. It also implement the java.util.Map interface which is Java's interface for a class which allows you to store key value pairs. This means you can pass HashMap to a method, which is expecting java.util.Map interface. 

1. What is the requirement for objects to be stored as keys and values in HashMap? (answer)
Both key and value object must implement equals() and hashcode() method if you intent to use them as key and value i HashMap. The hashcode() method of key is used to find the bucket location, where entry object is stored. Similarly, equals() method of key and value is used when you retrieve an object from HashMap. See Core Java for the Impatient for more details on how HashMap internally works. 

2. What is difference between HashMap and Hashtable in Java? (answer)
The key difference between them is that HashMap is not thread-safe while Hashtable is thread-safe. This tread-safety is achieved using synchronization, which also makes Hashtable slower than HashMap. Another worth noting difference is that HashMap was first added in Java 1.4 while Hashtable is present from the start of JDK. 


3. What is difference between HashMap and ConcurrentHashMap in Java? (answer)
The ConcurrentHashMap is an scalable and concurrent version of HashMap. The key difference again is same as it was in previous question, HashMap is not thread-safe but ConcurrentHashMap is thread-safe, though it is more scalable than Hashtable or synchronized HashMap because of its implementation e.g. it divides the map into several segments and it never lock whole map, instead only segments are locked when you add or remove entries from ConcurrentHashMap. You can learn more about its implementation on my post How ConcurrentHashMap works in Java.




4. How does a HashMap works in Java? (answer)
A HashMap works in the principle of hashing. The key object is linked with value objects using hash function. They also stored together as entry. It allows you to search for an object in O(1) time if you have key object. When you store an object into HashMap, the hash function is applied on its key to find the bucket location, which is nothing but the appropriate index in underlying array. It's nothing but hash table data structure, if you are not familiar with hash table, I suggest you reading a good book on data structures e.g. Introduction to Algorithms by Thomas H. Cormen. 

5. What is difference between HashMap and HashSet in Java? (answer)
HashMap is a Map, while HashSet is a Set. HashMap is used to store key value pairs, while HashSet can be used to store just one object e.g. keys. 

6. Which data structure is used to implement HashMap? (answer)
HashMap is implementation of hash table data structure but it uses array internally to store elements. The array is also known as bucket in context of HashMap. 


7. What is hash collision in HashMap? (answer)
When hash function return same bucket location for two different objects then its called collision because there is already an object stored at that location. In case of collision different collision resolution strategy is used to resolve it e.g. double hashing means another try to find a new location or chaining e.g. store both values in the same bucket location as linked list, which is what java.util.HashMap does to resolve collisions. 




8. What is difference between HashMap and TreeMap in Java? (answer)
The key difference between HashMap and TreeMap is the fact that HashMap is not ordered or sorted but TreeMap is a sorted Map, where key value pairs are stored in a sorted order imposed by Comparator (natural order) or Comparator (custom order). Another notable difference is that, apart from equals() and hashCode(). the key should also be Comparable to each other. 

Here is also a nice table which highlights key difference between HashMap, TreeMap, LinkedHashMap, and Hashtable in Java:

Top 40 Java HashMap Interview Questions and Answers for 3 to 5 Years Experienced



9. How many entries you can put into an HashMap? (answer)
You can put as many as you want, until you run out of memory but once you cross the threasold of Integer.MAX_VALUE you will start facing problems because the size method also return an int, which means if you store more than Intger.MAX_VALUE, the size method will return incorrect value. 


10. How do you remove an entry from HashMap while iterating over it? (answer)
You can remove an entry from HashMap by using the remove() method which is defined in the Iterator interface while iterating. The Set which is return by keySet() method of HashMap is a view of actual Map and any operation on this Set is also reflected on actual Map. For code example, you can see the full answer where I have showed step by step guide to remove a key, value and an entry from HashMap while iterating over it. 

11. Can you store null keys in HashMap? (answer)
This is one of the tricky questions as many people will think that HashMap doesn't allow null keys but that's not correct. You can store one null key in HashMap and multiple null values, they are stored at the 0th index which is the first entry but Hashtable, another similar class which is synchronized doesn't allow null key and storing null there will result in NullPointerException. This is also one of the key difference between Hashtable and HashMap in Java. 

12. How does HashMap handles null keys in Java? (answer)
As mentioned in earlier answer, they are all stored in 0th index of underlying bucket which is nothing but an array. The important point here to remember that HashMap allows null key in Java. 

13. Does HashMap is thread-safe? What will happen if you expose HashMap to multiple threads? (answer)
HashMap is not thread-safe as its not synchronized and hence its fast . If you will expose HashMap to multiple threads in a way where all of them only read then its fine but if they perform all kind of operation like read, write, delete etc then HashMap will not be able to sustain that its internal structure will break. This means, you may not be able to retrieve values, get incorrect value or result in deadlock. That's why its not advise to use HashMap in multi-threaded environment, instead you should use Hashtable or ConcurrentHashMap in Java. 

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

15. What is difference between HashMap and LinkedHashMap in Java? (answer)

16. How do you check if a key exists in HashMap? (answer)

17. How do you check if a value exists in HashMap? (answer)

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

19. Can you name some new methods added into HashMap in Java 8? (answer)

20. What is difference between size() and mappingCount() method of HashMap? (answer)

21. Does the iterator returned by HashMap is fail-safe or fail-fast? (answer)

22. How do you get all keys from HashMap in Java? (answer)
you can call the keySet() method which return all keys on the HashMap

23. How do you get all values from HashMap in Java? (answer)

24. What is difference between keySet, values, and entrySet methods of HashMap? (answer)

25. What is difference between HashMap and ArrayList in Java? (answer)

26. What is difference between HashMap and EnumMap in Java? (answer)

27. What is difference between HashMap and IdentityHashMap in Java? (answer)

28. How does HashMap handles collisions in Java? (answer)

29. How do you convert a JSON String to HashMap in Java? (answer)

30. How do you sort HashMap by keys in Java? (answer)

31. How do you sort HashMap by values in Java? (answer)
As I said, you cannot sort HashMap because it is an un-ordered collection, but you can capture all its values and sort them just like any other collection using Comparator and then store all entries in the order of values into a LinkedHashMap, which keeps mapping in the order they were added. 

32. How do you initialize HashMap by values in Java? (answer)
You can use this neat trick to initialize HashMap in Java. This is known as Double brace initialization pattern, it saves time but it is not encouraged because it creates an Anonymous class everytime you use it. 

33. How do you get key from a value in Java HashMap? (answer)
This is known as reverse lookup because you are trying to get a key from value and you should bear in mind that HashMap allows duplicate values means, more than one key can map to same value e.g. this method should return a set of keys. 

34. What is difference between HashMap and WeakHashMap in Java? (answer)
The main difference between HashMap and WeakHashMap is the fact that keys in WeakHashMap are wrapped inside WeakReference object, which means if an object is not referred anywhere else other than the Map itself, then it is subject to garbage collection.



35. How does get() method of HashMap works in Java? (answer)
get method works in the principle of hashing, you pass key then it uses key's hashcode() method to calculate hash and find the bucket location in underlying array. After that it uses key's equals() method to compare the object stored in the bucket as multiple objects can be stored in single bucket location due to collision, and then it return value for matching key.

36. How does put() method of HashMap works in Java? (answer)
put() method also work in the same way as get() method but we pass two objects to put, key and value. Just like get() , key's hashCode is used to calculate hash and find the bucket location in the underlying array for storing object and then both key and value is wrapped into one object called Entry and stored into that bucket location. Entry contains both key and value so that get() method can compare key and return value.

37. What is time complexity of get() and put() in HashMap? (answer)
Since HashMap is based upon hash table data structure complexity of get() and put() is O(1) but due to collision, all object can store into same location then it become linked list or binary tree, depending upon Java implementation store it and time complexity reduced to O(N) or O(LogN) depending upon entries are stored in Linked List or Binary tree.

38. What is the order of entries in HashMap? (answer)
HashMap doesn't guarantee any order, if you need ordering you can either use TreeMap which keeps keys in sorted order or LinkedHashMap which keeps entries in the order they are inserted into Map. 

39. Can you store duplicate keys in HashMap? What happens if you try to put a key which already exists in HashMap? (answer)
No, you cannot store a duplicate value in the HashMap. If you try to store a key which already exists in the Map then its value is updated with the new value and put() method returns the old value. 

40. Does HashMap allows duplicate values? (answer)
Yes, HashMap allows duplicate values and that's why the values() method, which return all values, return a Collection object and not a Set. 

And, if you need more HashMap questions for practice then you can also check following questions:
  1. How will you implement your own HashMap in Java?
    (hint - create your own class and use array)
  2. How do you call a HashMap method in Java?
    By using HashMap object, you can create an object using new() constructor
  3. How to store HashMap in Java?
    You can store HashMap in an object of Type Map or HashMap like
    Map<Integer, String> myMap = new HashMap<>();
  4. How to store database values in HashMap in Java?
  5. How to increment the value of a key in Hashmap Java?
  6. How to iterate an Arraylist inside a Hashmap using Java?
  7. How to convert integer array to Hashmap in Java?
  8. How to read json file in Java using Hashmap?
  9. How to print Hashmap in ascending order in Java?
  10. How to store in Hashmap Java?
  11. How to remove first element from Hashmap in Java?
  12. How to build a Hashmap in Java?
  13. Is Hashmap an object in Java?
  14. How to read XML file and store in Hashmap Java?
  15. How to compare single Hashmap values in Java 8?
  16. How to put two Arraylist in Hashmap in Java?
  17. How to refresh Hashmap in Java?
  18. How to implement Hashmap in Java without using collection?
  19. How to convert Hashmap to XML in Java?
  20. How to write Hashmap to excel in Java?
  21. How to store values from Excel to Hashmap in Java?
  22. How do you count the number of occurrences of an element in a Hashmap in Java?
  23. How to retrieve data from database using Hashmap in Java?
  24. How will you implement your own HashMap in Java How will you handle collision of keys?
  25. How to read data from Excel using HashMap in Java?

That's all about some of the essential HashMap interview questions from Java developer job interviews. These questions will not only help you to do well on your job interview but also help you to learn and understand HashMap better, which is very important for a Java developer. It also encourage you to learn more about HashMap e.g. how they are implemented internally, what are the requirements for key and value objects, performance of HashMap, thread-safety, immutability and other important properties of HashMap. 

Other Java Interview Questions you may like to explore for practice
  • Top 10 Spring Framework Interview Questions with Answers (see here)
  • 15 Data Structure and Algorithm Questions from Java Interviews (read here)
  • 20 Spring Boot Interview Questions with Answers (spring boot questions)
  • 20 Java Design Pattern Questions asked on Interviews (see here)
  • 10 Servlet Interview Questions with Answers (see here)
  • 10 popular Struts Interview Questions for Java developers (list)
  • 20 jQuery Interview Questions for Java Web Developers (list)
  • 20 Tibco Rendezvous and EMS Interview Questions (read more)
  • 10 Oracle Interview Questions for Java developers (see here)
  • Top 10 JSP Questions  from J2EE Interviews (read here)
  • Top 10 EJB Interview Questions and Answers (see here)
  • 12 RESTful Web Services Questions from Interviews (read here)
  • Top 10 JMS and MQ Series Interview Questions and Answers (list)
  • 15 Java NIO and Networking Interview Questions with Answers (see here)
  • 10 JDBC Interview Questions for Java Programmers (questions)
  • Top 10 XSLT Interview Questions with Answers (read more)
  • 10 XML Interview Questions for Java Programmers (read here)
  • Top 10 Trick Java Interview Questions and Answers (see here)
  • 10 Hibernate Interview Questions for Java EE developers (see here)
  • Top 40 Core Java Phone Interview Questions with Answers (list)
  • 15 Microservice Interview Questions with Answers (Microservice questions)

Thanks for reading this article. If you like these Java HashMap interview questions and their answers then please share with your friends and colleagues. If you have any question, feedback or any doubt about these questions/answers, please drop a comment.

P. S. - If you are preparing for Java interviews and looking for more resources then you can also check these best Java Interview preparation courses from Udemy, Coursera and other websites. It contains both books and online courses for complete preparation. 

No comments:

Post a Comment