Thursday, October 31, 2019

Top 21 Coffee Hashmap Interview Questions As Well As Answers

The java.util.HashMap is 1 of the workhorses of JDK. Along alongside ArrayList, it is 1 of the most used classes from Java's collection framework. There is hardly a real-world Java project, where I haven't seen the usage of HashMap. It is an implementation of hash tabular array information construction together with it's non a surprise that HashMap is so useful, as individual has rightly said, "if you lot could direct maintain only 1 information structure, arrive a hash table". The hash tabular array information construction allows you lot to search for a value inwards O(1) fourth dimension if you lot direct maintain key. In Java, at that spot are several implementations of hash tabular array information construction exists similar Hashtable, ConcurrentHashMap, LinkedHashMap, etc but HashMap is your full general role map.

Though, if you lot direct maintain a special demand you lot tin usage other hash tabular array implementations available inwards JDK. For example, if you lot desire to save the lodge of mapping together with so you lot tin consider using LinkedHashMap. If you lot desire to croak on mappings sorted together with so you lot tin usage TreeMap, which is a sorted map implementation.

Similarly, if you lot demand a hash tabular array implementation which is thread-safe together with tin hold upwards used inwards a concurrent application without compromising the Scalability together with so consider using a ConcurrentHashMap from JDK 5.

Btw, if you lot are novel to Java basis together with JDK API inwards particular, I advise you lot to offset croak through a comprehensive Java course of didactics similar The Complete Java Masterclass on Udemy. That volition non exclusively aid you lot to produce good on interviews but besides aid you lot to sympathise the fundamentals better.





Java HashMap Interview Questions

Here is my listing of HashMap questions from Java Interviews. This listing includes questions based on the internal implementation of HashMap, the Map API, how you lot usage HashMap together with mutual best practices spell using HashMap inwards a Java application.


1. How does put() method of HashMap plant inwards Java? (answer)
The put() method of HashMap plant inwards the regulation of hashing. It is responsible for storing an object into the backend array. The hashcode() method is used inwards conjunction alongside a hash portion to respect the right location for the object into the bucket. If a collision occurs together with so the entry object which contains both key together with value is added to a linked listing and that linked listing is stored into the bucket location.


2. What is the requirement for an object to hold upwards used as key or value inwards HashMap? (answer)
The key or value object must implement equals() together with hashcode() method. The hash code is used when you lot insert the key object into the map spell equals are used when you lot endeavor to shout upwards a value from the map.


3. What volition direct house if you lot endeavor to shop a key which is already nowadays inwards HashMap? (answer)
If you lot shop an existing key inwards the HashMap together with so it volition override the one-time value alongside the novel value together with put() volition render the one-time value. There volition non hold upwards whatsoever exception or error.


4. Can you lot shop a cipher key inwards Java HashMap? (answer)
Yes, HashMap allows 1 cipher key which is stored at the offset location of bucket array e.g. bucket[0] = value. The HashMap doesn't telephone phone hashCode() on cipher key because it volition throw NullPointerException, thence when a user telephone phone get() method alongside cipher together with so the value of the offset index is returned.

5. Can you lot shop a cipher value within HashMap inwards Java? (answer)
Yes, HashMap besides allows cipher value, you lot tin shop as many cipher values as you lot desire as shown inwards the hashmap illustration post inwards this blog.


6. How does HashMap direct maintain collisions inwards Java? (answer)
The java.util.HashMap uses chaining to direct maintain collisions, which agency novel entries, an object which contains both key together with values, are stored inwards a linked listing along alongside the existing value together with and so that linked listing is stored inwards the bucket location.

In the worst case, where all key has the same hashcode, your hash tabular array volition hold upwards turned into a linked listing together with searching a value volition direct maintain O(n) fourth dimension as opposed to O(1) time.

If you lot desire to larn to a greater extent than most hash tabular array information structure, I advise you lot consult a practiced information construction together with algorithm course of didactics like Data Structures together with Algorithms: Deep Dive Using Java on Udemy, which non exclusively embrace basic information construction similar array, linked list, binary tree, together with hash tabular array but besides advanced concepts similar O(n) sorting algorithms, Radix sort, Counting sort, etc.

 it is 1 of the most used classes from Java Top 21 Java HashMap Interview Questions together with Answers



7. Which information construction HashMap represents? (answer)
The HashMap is an implementation of hash tabular array information construction which is idle for mapping 1 value to other similar id to mention as you lot tin search for value inwards O(1) fourth dimension if you lot direct maintain the key.


8. Which information construction is used to implement HashMap inwards Java? (answer)
Even though HashMap represents a hash table, it is internally implemented past times using an array together with linked listing information construction inwards JDK.  The array information construction is used as a bucket spell a linked list is used to shop all mappings which province inwards the same bucket. From Java 8 onwards, the linked listing is dynamically replaced past times binary search tree, 1 time a number of elements inwards the linked listing cross a surely threshold to improve performance.


9. Can you lot shop a duplicate key inwards HashMap? (answer)
No, you lot cannot insert duplicate keys inwards HashMap, it doesn't allow duplicate keys. If you lot endeavor to insert an existing key alongside novel or same value together with so it volition override the one-time value but size of HashMap volition non modify i.e. it volition stay the same. This is 1 of the argue when you lot acquire all keys from the HashMap past times calling keySet() it returns a Set, non a Collection because Set doesn't allow duplicates.


10. Can you lot shop the duplicate value inwards Java HashMap? (answer)
Yes, you lot tin set duplicate values inwards HashMap of Java. It allows duplicate values, that's why when you lot shout upwards all values from the Hashmap past times calling values() method it returns a Collection together with non Set. Worth noting is that it doesn't render List because HashMap doesn't supply whatsoever ordering guarantee for key or value.

If you lot desire to explore, you lot tin besides see answer)
No, HashMap is non thread-safe inwards Java. You should non portion a HashMap alongside multiple threads if 1 or to a greater extent than thread is modifying the HashMap e.g. inserting or removing a map. Though, you lot tin easily portion a read-only HashMap.


12. What volition direct house if you lot usage HashMap inwards a multithreaded Java application? (answer)
If you lot usage HashMap inwards a multithreaded environs inwards such a way that multiple threads structurally modify the map e.g. add, take away or modify mapping together with so the internal information construction of HashMap may acquire corrupt similar or so links may croak missing, or so may indicate to wrong entries together with the map itself may croak completely useless. Hence, it is advised non to usage HashMap inwards the concurrent application, instead, you lot should usage a thread-safe map e.g. ConcurrentHashMap or Hashtable.


13. What are different ways to iterate over HashMap inwards Java? (answer)
Here are or so of the ways to iterate over HashMap inwards Java:
past times using keySet together with iterator
past times using entrySet together with iterator
past times using entrySet together with enhanced for loop
past times using keySet together with get() method

You tin come across this article for an illustration of each of these ways to traverse a HashMap inwards Java.


14. How produce you lot take away a mapping spell iterating over HashMap inwards Java? (answer)
Even though HashMap provides remove() method to take away a key together with a key/value pair, you lot cannot usage them to take away a mapping spell traversing a HashMap, instead, you lot demand to usage the Iterator's take away method to take away a mapping as shown inwards the next example:

Iterator itr = map.entrySet().iterator();  while(itr.hasNext()){   Map.Entry electrical flow = itr.next();    if(current.getKey().equals("matching"){      itr.remove(); // this volition take away the electrical flow entry.   } }

You tin come across that nosotros direct maintain used Iterator.remove() method to take away the electrical flow entry spell traversing the map. See this article to larn to a greater extent than most it.


15. In which lodge mappings are stored inwards HashMap? (answer)
Random lodge because HashMap doesn't supply whatsoever ordering guarantee for keys, values, or entries. When you lot iterate over a HashMap, you lot may acquire the different lodge every fourth dimension you lot iterate over it.





16. Can you lot form HashMap inwards Java? (answer)
No, you lot cannot form a HashMap because dissimilar List it is non an ordered collection. Albeit, you lot tin form contents of HashMap past times keys, values or past times entries past times sorting together with and so storing the resultant into an ordered map similar LinkedHashMap or a sorted map e.g. TreeMap.


17. What is the charge factor inwards HashMap? (answer)
Influenza A virus subtype H5N1 charge factor is a number which controls the resizing of HashMap when a number of elements inwards the HashMap cross the charge factor e.g. if the charge factor is 0.75 together with when becoming to a greater extent than than 75% amount together with so resizing trigger which involves array copy.


18. How does resizing happens inwards HashMap? (answer)
The resizing happens when the map becomes amount or when the size of the map crosses the charge factor. For example, if the charge factor is 0.75 together with and so croak to a greater extent than than 75% amount together with so resizing trigger which involves array copy. First, the size of the bucket is doubled together with and so one-time entries are copied into a novel bucket.


19. How many entries you lot tin shop inwards HashMap? What is the maximum limit? (answer)
There is no maximum bound for HashMap, you lot tin shop as many entries as you lot desire because when you lot run out of the bucket, entries volition hold upwards added to a linked listing which tin back upwards an infinite number of entries, of course of didactics until you lot exhaust all the retentiveness you lot have.

Btw, the size() method of HashMap render an int, which has a limit, 1 time a number of entries cross the limit, size() volition overflow together with if your computer program relies on that together with so it volition break.

This number has been addressed inwards JDK 8 past times introducing a novel method called mappingCount() which returns a long value. So, you lot should usage mappingCount() for large maps. See Java SE 8 for Really Impatient to larn to a greater extent than most novel methods introduced inwards existing interfaces inwards JDK 8.

 it is 1 of the most used classes from Java Top 21 Java HashMap Interview Questions together with Answers


21. What is the divergence betwixt capacity together with size of HashMap inwards Java? (answer)
The capacity denotes how many entries HashMap tin shop together with size denotes how many mappings or key/value duo is currently present.


21. What volition direct house if ii different keys of HashMap render same hashcode()? (answer)
If ii keys of HashMap render same hash code together with so they volition destination upwards inwards the same bucket, thence collision volition occur. They volition hold upwards stored inwards a linked listing together.


That's all most or so of the of import Java HashMap interview questions. I direct maintain tried to reply them as well, but if you lot disagree alongside an reply together with so experience complimentary to comment. Since HashMap is a rattling of import shape inwards Java together with as of import from Java interview indicate of view, it pays to sympathise this shape together with its implementation inwards deep.

Further Learning
The Complete Java Masterclass
list)
  • 19 Java Overloading together with Overriding Interview Questions (list)
  • 15 Java NIO together with Networking Interview Questions alongside Answers (see here)
  • 21 Java ArrayList Interview Questions alongside Answers (list)
  • 20+ String Coding Problems from Interviews (questions)
  • 21 Java Final modifier Interview Questions (list)
  • 21 Java Inheritance Interview Questions alongside answers (list)
  • 75 Coding Interview Questions for Programmers (questions
  • 10 Date, Time, together with Calendar based Interview Questions alongside answers (list)
  • 5 main() method interview questions (list)
  • 15 SQL together with UNIX questions from Java Interviews (list)
  • 22 array concept interview questions from Java (list)
  • 15 Java Enum based Interview Questions (list)
  • 50+ Data Structure together with Algorithms Interview Questions (questions)

  • These questions volition non exclusively aid you lot to sympathise HashMap amend but besides encourage you lot to respect out to a greater extent than most HashMap, it's Java implementation together with hash tabular array information construction inwards general. If you lot direct maintain whatsoever other HashMap based Java questions, which was asked to you lot inwards an interview, experience complimentary to portion alongside us.

    P. S. - If you lot are preparing for Java Interviews together with looking for or so interesting questions for do together with so you lot tin besides depository fiscal establishment check out this Java Interview Guide: 200+ Interview Questions together with Answers course, which contains to a greater extent than than 200+ real-world questions from Java interviews together with their explanation.

    No comments:

    Post a Comment