Some questions and answers about HashMap

Source: Internet
Author: User

"Original address": http://www.importnew.com/7099.html

How does HashMap work, and howdoes the HashMap get () method work?

HashMap is based on the principle of hashing, we use put (key, value) to store objects into HashMap, using get (key) to get objects from 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 locate the bucket position to store the entry object.

What happens when a hashcode of two objects is the same?

Because hashcode are the same, their buckets are in the same position and ' collisions ' will occur. Because HashMap uses a linked list to store objects, this entry (Map.entry object with key-value pairs) is stored in the linked list.

How do you get a value object if the hashcode of the two keys are the same?

When we call the Get () method, HashMap will find the bucket position using the hashcode of the key object, if there are two value objects stored in the same bucket, because HashMap stores the key-value pairs in the linked list, it will traverse the list, call Keys.equals () method to find the correct node in the linked list and finally find the value object to find.

In many cases, interviewers will make mistakes in this link because they confuse the hashcode () and Equals () methods. Because Hashcode () occurs before this, the Equals () method appears only when the value object is fetched. Some good developers will point out that using immutable, declared final objects, and using the appropriate equals () and Hashcode () methods, will reduce collisions and increase efficiency. Immutability makes it possible to cache hashcode of different keys, which increases the overall speed of getting objects, and using wrapper classes like String,interger as Keys is a good choice.

What if the size of the hashmap exceeds the capacity defined by the load factor (load factor)?

The default load factor size is 0.75, which means that when a map fills 75% buckets, as with other collection classes (such as ArrayList, etc.), it will create a twice-fold bucket array of the original HashMap size to resize the map. And put the original object in a new bucket array. This process is called rehashing because it calls the hash method to find the new bucket position.

Do you know what's wrong with resizing hashmap?

In the case of multithreading, conditional competition (race condition) may occur.

When resizing the HashMap, there is a conditional competition, because if two threads find that HashMap needs resizing, they try resizing at the same time. During resizing, the order of the elements stored in the list is reversed, because when moving to a new bucket position, HashMap does not place the element at the end of the list, but rather on the head, in order to avoid trailing traversal (tail traversing). If the conditional competition happens, then the cycle is dead. This time, you can question the interviewer, why so strange, in a multi-threaded environment to use HashMap it?

why does a wrapper class like String, Interger, fit as a key?

String, Interger such wrapper class as the HashMap key is more suitable, and string is most commonly used. Because the string is immutable and final, the Equals () and Hashcode () methods have been rewritten. Other wrapper classes also have this feature. Immutability is necessary because, in order to calculate hashcode (), it is important to prevent the key value from changing, and if the key value returns a different hashcode when it is placed and obtained, then you cannot find the object you want from the HashMap. Immutability has other advantages, such as thread safety. If you can make sure that hashcode is constant by simply declaring a field as final, then please do so. Because the Equals () and Hashcode () methods are used when acquiring the object, it is important that the key object is correctly overridden by the two methods. If two unequal objects return different hashcode, then the chances of collisions are smaller, which can improve the performance of HashMap.

Can we use the custom object as a key?

This is an extension of the previous question. Of course you might use any object as a key, as long as it adheres to the definition rules of the Equals () and Hashcode () methods, and will no longer change when the object is inserted into the map. If the custom object is immutable, it already satisfies the condition as a key, because it cannot be changed once it is created.

Can we use Cocurrenthashmap instead of Hashtable?

This is another very popular face test, because concurrenthashmap more and more people use. We know that Hashtable is synchronized, but the Concurrenthashmap synchronization performance is better because it locks only part of the map based on the sync level. Concurrenthashmap can of course take the place of HashTable, but HashTable provides stronger thread safety. Check out this blog to see the difference between Hashtable and Concurrenthashmap.

I personally like this problem because of the depth and breadth of the problem, and not directly related to different concepts. Let's take a look at these questions to design what knowledge points:

    • The concept of hashing
    • Methods of solving collisions in HashMap
    • The application of Equals () and hashcode (), and their importance in HashMap
    • The benefits of immutable objects
    • HashMap Multi-threaded conditional competition
    • Resize the HashMap
Summarize how the HashMap works

HashMap based on the hashing principle, we store and retrieve objects through the 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, allowing the bucket position to be found to store the value object. When the object is fetched, the correct key-value pair is found by the Equals () method of the Key object, and then the value object is returned. HashMap uses a linked list to solve the collision problem, and when a collision occurs, the object is stored in the next node of the list. HashMap stores key-value pairs of objects in each linked list node.

What happens when the hashcode of two different key objects is the same? They are stored in a linked list of the same bucket location. The Equals () method of the Key object is used to locate the key-value pair.

Because HashMap has many benefits, I used HashMap as a cache in e-commerce applications. Because of the many uses of Java in the financial sector, and for performance reasons, we often use HashMap and concurrenthashmap.

More articles about HashMap:

    • The difference between HashMap and Hashtable
    • The difference between HashMap and HashSet

Some questions and answers about HashMap

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.