The working principle of HashMap and the working principle of HashMap
The working principle of HashMap is a common Java interview question in recent years. Almost every Java programmer knows HashMap, where to use HashMap, and the difference between Hashtable and HashMap. Why is this question so special? It is because the depth of this question is very deep. This topic is often used in advanced or advanced interviews. Investment banks prefer to ask this question and even require you to implement HashMap to evaluate your programming capabilities. The introduction of ConcurrentHashMap and other synchronization sets makes this question more complex. Let's start our journey!
Let's start with some simple questions.
"Have you used HashMap ?" "What is HashMap? Why do you use it ?"
Almost everyone will answer "yes" and then answer some features of HashMap. For example, HashMap can accept null key values and values, but Hashtable cannot; HashMap is non-synchronized; HashMap is fast; and HashMap stores key-value pairs. This shows that you have used HashMap and are quite familiar with it. However, the interviewer was in a hurry. From now on, he began to ask some questions about the drill and more basic details about HashMap. The interviewer may ask the following questions:
"Do you know how HashMap works ?" "Do you know how the get () method of HashMap works ?"
You may reply, "I have not checked the standard Java API in detail. You can check the Java source code or Open JDK ." "I can use Google to find the answer ."
However, some interviewers may give the answer, "HashMap is based on the hashing principle. We use put (key, value) to store objects in HashMap, and get (key) is used) obtain objects from HashMap. When we pass the key and value to the put () method, we first call the hashCode () method on the key. The returned hashCode is used to locate the bucket location to store the Entry object ." The key point here is that HashMap stores key objects and value objects in the bucket as Map. Entry. This helps you understand the logic of getting objects. If you do not realize this or mistakenly think that you only store values in the bucket, you will not answer how to obtain the object logic from HashMap. This answer is quite correct. It also shows that the interviewer does know how hashing and HashMap work. However, this is just the beginning of the story. When the interviewer joins some actual scenarios that Java programmers encounter every day, the wrong answers are frequently answered. The next problem may be about collision detection in HashMap and the solution to the collision:
"What happens when the hashcode of the two objects is the same ?"From here on, the real confusion begins. Some interviewers will answer that because the hashcode is the same, the two objects are equal, and HashMap will throw an exception or not store them. Then the interviewer may remind them that there are two methods, equals () and hashCode (), and tell them that they may not be the same even if the hashcode is the same. Some interviewers may give up on this, while others can continue advancing. They replied, "because the hashcode is the same, their buckets are in the same location, and 'collision 'occurs. Because HashMap uses a linked list to store objects, this Entry (containing Map. Entry objects with key-value pairs) is stored in the linked list ." This answer is very reasonable. Although there are many ways to deal with collision, this method is the simplest, and it is also the HashMap processing method. But the story is not over yet. The interviewer will continue to ask:
"If the hashcode of the two keys is the same, how do you get the value object ?"The interviewer will answer: when we call the get () method, HashMap will use the hashcode of the key object to locate the bucket location and then obtain the value object. The interviewer reminds him that if two value objects are stored in the same bucket, he will repeat the table until the value object is found. The interviewer will ask how do you determine to find the value object because you have no value object for comparison? It is impossible for the interviewer to answer this question unless HashMap stores key-value pairs in the linked list.
Some interviewers who remember this important knowledge point will say that after finding the bucket location, they will call the keys. equals () method to find the correct node in the linked list and finally find the value object to be found. The perfect answer!
In many cases, the interviewer will make an error in this step because they confuse the hashCode () and equals () methods. Previously, hashCode () appeared frequently, while the equals () method only appeared when obtaining value objects. Some excellent developers will point out that they use immutable and declared final objects and adopt the appropriate equals () and hashCode () methods to reduce the occurrence of collisions, improve efficiency. Immutable: The hashcode of different keys can be cached, which increases the speed of the entire object to be retrieved. Using wrapper classes such as String and Interger as keys is a good choice.
If you think this is over, you will be surprised when you hear this question."What if the size of HashMap exceeds the capacity defined by the load factor ?"Unless you really know how HashMap works, you will not be able to answer this question. The default load factor is 0.75, that is, when a map fills up 75% buckets, it is the same as other collection classes (such as ArrayList, A bucket array of twice the size of the original HashMap will be created to re-adjust the map size and put the original object into the new bucket array. This process is called rehashing because it calls the hash method to locate the new bucket location.
If you can answer this question, the following question comes:"Do you know what is wrong with adjusting the HashMap size ?"You may not be able to answer this question. At this time, the interviewer will remind you that race condition may occur when multithreading occurs ).
When the HashMap size is re-adjusted, conditional competition exists, because if both threads find that HashMap needs to be re-adjusted, they will try to adjust the size at the same time. In the process of resizing, the order of elements stored in the linked list is reversed, because when moving to the new bucket location, HashMap does not put the elements at the end of the linked list, but in the header, this is to avoid tail traversal ). If the condition competition happens, it will be an endless loop. At this time, you can ask the interviewer why is HashMap used in a multi-threaded environment so strange? :)
Enthusiastic readers have contributed more questions about HashMap:
I personally like this problem because its depth and breadth do not directly involve different concepts. Let's take a look at the knowledge points of these questions:
- Hashing Concept
- How to solve the collision in HashMap
- Applications of equals () and hashCode (), and their importance in HashMap
- Benefits of immutable objects
- Conditional competition for HashMap Multithreading
- Re-adjust the HashMap size
Summarize the working principles of HashMap
Based on the hashing principle, HashMap stores and obtains objects through put () and get () methods. When we pass a key-value pair to the put () method, it calls the hashCode () method of the key object to calculate the hashcode, and then finds the bucket location to store the value object. When obtaining an object, find the correct key-value pair through the equals () method of the key object, and then return the object. HashMap uses the linked list to solve the collision problem. When a collision occurs, the object will be stored in the next node of the linked list. HashMap stores key-Value Pair objects in each linked list node.
What happens when the hashcode of two different key objects is the same? They are stored in the linked list at the same bucket location. The equals () method of the key object is used to find the key-value pair.
Because HashMap has many benefits, I used HashMap as a cache in e-commerce applications. Because Java is widely used in the financial field, we often use HashMap and ConcurrentHashMap for performance considerations.
Original article: Javarevisited Translation: ImportNew.com-Tang xiaojuan
Http://www.importnew.com/7099.html.