To be honest, the degree of understanding of Java collections is considered qualified, even if it is a big cow among big cows, a big god among big gods, what is the advantage of knowing the principle of collection, can it be said that if you want to rewrite Java collections, write your own performance? Is it better?
It’s no use but! If you don’t answer, then you can only go back and wait for the notice… So do you want to give the interviewer some work? Maybe we only need to know that HashMap is an asynchronous implementation of the Map interface based on the hash table. This implementation provides all optional mapping operations and allows the use of null values and null keys. This class does not guarantee the order of the mapping, especially it does not guarantee that the order will last forever. HashMap is actually a “linked list hash” data structure, that is, a combination of array and linked list. Why do you need to ask the principle? Another way to ask is how HashMap finds and stores values efficiently.. HashMap uses Map.Entry internally to store the key and value, uses the put(key, value) method to store the value, and uses get( key) method to find the value. Share a 24W Java interview manual, which includes network protocol, Java basics, advanced, string, collection, concurrency, JVM, data structure, algorithm, MySQL, Redis, Mongo, Spring, SpringBoot, MyBatis, SpringCloud, Linux And various middleware (Dubbo, Nginx, Zookeeper, MQ, Kafka, ElasticSearch), etc… Link: Fatty Tiger A: It took a month to compile a 240,000-word Java interview manual. For example, often in interviews You will encounter HashMap related questions: 1. “Have you used HashMap? What is HashMap? Why do you use it?” Almost everyone will answer “Yes” and then answer some of the characteristics of HashMap, such as HashMap can accept null Key-value and value, while Hashtable cannot; HashMap is non-synchronized; HashMap is fast; and HashMap stores key-value pairs and so on. This shows that you have used HashMap and are quite familiar with it. But the interviewer took a sharp turn and started asking some tricky questions from now on, about more basic details about HashMap. The interviewer may ask the following questions: 2. “Do you know the working principle of HashMap? Do you know the working principle of the get() method of HashMap?” You may answer “I did not check the standard Java API in detail, you You can look at the Java source code or Open JDK.” “I can use Google to find the answer.” But some interviewers may be able to give the answer, “HashMap is based on the principle of hashing, we use put (key, value) to store objects to HashMap , Use get(key) to get the object from the HashMap. When we pass the key and value to the put() method, we first call the hashCode() method on the key, and the returned hashCode is used to find the bucket location to store the Entry object.” The key point here is to point out that HashMap stores key objects and value objects in the bucket as Map.Entry. This is helpful to understand the logic of obtaining objects. If you are not aware of this, or mistakenly believe that only the value is stored in the bucket, you will not answer the logic of how to get the object from the HashMap. This answer is quite correct, and it also shows that the interviewer really knows the working principle of hashing and HashMap. But this is only the beginning of the story. When the interviewer added some actual scenes that Java programmers encounter every day, wrong answers frequently appeared. The next question may be about collision detection in HashMap and collision resolution: 3. “What happens when the hashcodes of two objects are the same?” From here, the real confusion begins. Some interviewers will Answer Because the hashcode is the same, the two objects are equal, the HashMap will throw an exception, or they will not be stored. Then the interviewer may remind them that there are equals() and hashCode() methods, and tell them that even if the two objects have the same hashcode, they may not be equal. Some interviewers may give up on this, while others can continue to advance. They answered “Because the hashcode is the same, so their bucket locations are the same, and’collision’ will occur. Because HashMap uses a linked list to store objects, this Entry (contains key-value pairs) The Map.Entry object) will be stored in the linked list.” This answer is very reasonable. Although there are many ways to deal with collisions, this method is the simplest, and it is exactly the way to deal with HashMap. But the story is not over yet, the interviewer will continue to ask: 4. “If the hashcodes of the two keys are 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 Find the bucket location, and then get the value object. The interviewer reminded him that if there are two value objects stored in the same bucket, he gives the answer: it will traverse the linked list until the value object is found. The interviewer will ask because you don’t have a value object to compare, how are you sure to find a value object? Unless interviewees until HashMap stores key-value pairs in the linked list, they will not be able to answer this question. 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 they are looking for. The perfect answer! In many cases, interviewers will make mistakes in this link because they confuse the hashCode() and equals() methods. Because the hashCode() appeared repeatedly before this, and the equals() method only appeared when the value object was obtained. Some good developers will point out that the use of immutable, declared final objects, and the use of appropriate equals() and hashCode() methods will reduce collisions and improve efficiency. Immutability makes it possible to cache the hashcode of different keys, which will increase the speed of the entire object acquisition. It is a very good choice to use wrapper classes such as String and Interger as the key. If you think it’s over here, you will be surprised when you hear the following question. 5. “What if the size of HashMap exceeds the capacity defined by load factor?” Unless you really know how HashMap works, you won’t be able to answer this question. The default load factor size is 0.75, that is to say, when a map fills up 75% of the bucket, like other collections (such as ArrayList, etc.), a bucket array twice the size of the original HashMap will be created to recreate Adjust the size of the map and put the original objects into the new bucket array. This process is called rehashing, because it calls the hash method to find the new bucket location. If you can answer this question, the following questions come: 6. “Do you know what is wrong with resizing the HashMap?” You may not be able to answer it. At this time, the interviewer will remind you that when you are multi-threaded, it may Generate a race condition. When the HashMap is resized, there is indeed a race condition, because if both threads find that the HashMap needs to be resized, they will try to resize at the same time. In the process of resizing, the order of the elements stored in the linked list will be reversed, because when moving to a new bucket position, HashMap will not put the elements at the end of the linked list, but at the head. This is To avoid tail traversing. If conditional competition occurs, then there is an endless loop. At this time, you can ask the interviewer, why is it so strange to use HashMap in a multi-threaded environment? ) Supplement: More questions about HashMap: 1. Why are wrapper classes such as String and Interger suitable as keys? Wrapper classes such as String and Interger are suitable as the keys of HashMap, and String is the most commonly used. Because String is immutable and final, and the equals() and hashCode() methods have been rewritten. Other wrapper classes also have this feature. Immutability is necessary because in order to calculate the hashCode(), the key value must be prevented from changing. If the key value returns a different hashcode when it is put in and when it is obtained, then the object you want cannot be found in the HashMap. Immutability has other advantages such as thread safety. If you can guarantee that the hashCode is constant just by declaring a field as final, then please do so. Because the equals() and hashCode() methods are used when obtaining the object, it is very important that the key object rewrite these two methods correctly. If two unequal objects return different hashcodes, the chance of collision will be smaller, which can improve the performance of HashMap. 2. Can we use custom objects as keys? This is an extension of the previous question. Of course, you may use any object as a key, as long as it complies with the definition rules of equals() and hashCode(), and the object will not change after it is inserted into the Map. If this custom object is immutable, then it has already met the condition of being a key, because it cannot be changed after it is created. 3. Can we use CocurrentHashMap instead of Hashtable? This is another very popular interview question, because more and more people use ConcurrentHashMap. We know that Hashtable is synchronized, but ConcurrentHashMap has better synchronization performance because it only locks a part of the map based on the synchronization level. ConcurrentHashMap can certainly replace HashTable, but HashTable provides stronger thread safety. I personally like this question very much, because the depth and breadth of this question do not directly involve different concepts. Let’s take a look at the knowledge points of these problems: the concept of hashing, the application of equals() and hashCode() to solve collisions in HashMap, and their importance in HashMap. The benefits of immutable objects. HashMap multi-threaded conditional competition Re-adjust the size of HashMap. The working principle of HashMap HashMap is based on the principle of hashing. We store and obtain objects through put() and get() methods. When we pass the 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 value object. HashMap uses a 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 hashcodes of two different key objects are the same? They will be stored in a linked list in the same bucket location. The equals() method of the key object is used to find key-value pairs.