JAVA HashMap Knowledge Collation

Source: Internet
Author: User
Tags concurrentmodificationexception

The comparison between HashMap and Hashtable is a common problem in the Java interview to test whether the programmer can use the collection class correctly and whether it can be used in a variety of ways to solve problems. The work of HashMap, the comparison of ArrayList with vectors, and the problem are the most classic questions about the Java Collection framework. Hashtable is an obsolete collection class that exists in the Java API for a long time. has been rewritten in Java 4 to implement the map interface, so it has since become part of the Java Collection framework. Hashtable and HashMap are fairly easy to ask in the Java interview, and even become the most frequently asked questions in the collection framework interview, so don't forget to prepare the question before you take any Java interview.

In this article, we will see not only the differences between HashMap and Hashtable, but also the similarities between them.

The difference between HashMap and Hashtable

HashMap and Hashtable both implement the map interface, but decide which one to use before you start to figure out the difference between them. The main differences are: thread safety, Synchronization (synchronization), and speed.

    1. HashMap can be almost equivalent to Hashtable, except that HashMap is non-synchronized and can accept null (HashMap can accept null key value (key) and values (value), and Hashtable does not).
    2. HashMap is non-synchronized, and Hashtable is synchronized, which means that Hashtable is thread-safe, multiple threads can share a hashtable, and if there is no proper synchronization, Multiple threads are not able to share hashmap. Java 5 provides Concurrenthashmap, which is an alternative to Hashtable that is better than Hashtable extensibility.
    3. Another difference is that the HashMap iterator (Iterator) is a fail-fast iterator, and Hashtable's enumerator iterator is not fail-fast. So when there are other threads that change the structure of the HashMap (add or remove elements), the concurrentmodificationexception will be thrown, but the remove () of the iterator itself The Concurrentmodificationexception method removes the element without throwing an exception. But this is not a certain behavior, depends on the JVM. This one is also the difference between enumeration and iterator.
    4. Because Hashtable is thread-safe and synchronized, it is slower than HashMap in a single-threaded environment. If you don't need to sync and just need a single thread, it's better to use HashMap performance than Hashtable.
    5. HashMap cannot guarantee that the order of elements in the map will be constant over time.

Some important terms to note:

1) sychronized means that only one thread at a time can change Hashtable. This means that any thread that wants to update Hashtable first obtains a sync lock, and the other thread waits until the sync lock is released before it can get the Sync lock update Hashtable again.

2) Fail-Safe and iterator iterators are related. If a collection object creates iterator or Listiterator, and then other threads try to "structurally" change the collection object, the Concurrentmodificationexception exception is thrown. But other threads can change the collection object through the Set () method, because this does not change the collection from "structurally". However, if you have changed the structure and then called the Set () method, the IllegalArgumentException exception will be thrown.

3) structural changes mean deleting or inserting an element, which affects the structure of the map.

Can we get hashmap in sync?

The HashMap can be synchronized using the following statement:

Map m = Collections.synchronizemap (HASHMAP);

Conclusion

Hashtable and HashMap have several major differences: thread safety and speed. Use Hashtable only when you need full thread safety, and if you use Java 5 or later, use the Concurrenthashmap bar.

From

Let's start with some simple questions.

"Have you ever used HashMap?" "What is HashMap?" Why did you use it? ”

Almost everyone will answer "yes" and then answer some of the features of HashMap, such as HashMap can accept null key value and value, while Hashtable cannot; HashMap is 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 came to a precipitous start, asking some tricky questions about the details of HashMap's more basic. The interviewer may ask the following questions:

"Do you know how HashMap works?" "Do you know how the HashMap get () method works?" ”

You may be able to answer, "I didn't look up the standard Java API, you can look at 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 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. "The key point here is to point out that HashMap is storing key objects and value objects in buckets as Map.entry. This helps to understand the logic of acquiring objects. If you are not aware of this, or if you mistakenly think that you only store values in buckets, you will not be able to answer the logic of getting objects from HashMap. The answer is quite correct and shows that the interviewer really knows how hashing and hashmap work. But this is just the beginning of the story, and when the interviewer joins some real-world scenarios that Java programmers encounter every day, the wrong answer is frequent. The next question may be about collision detection (collision detection) in HashMap and the resolution of collisions:

"What happens when a hashcode of two objects is the same?" "From here, the real confusion begins, and some interviewers will answer because Hashcode is the same, so two objects are equal, HashMap will throw an exception, or it will not store them. The interviewer may then remind them of the Equals () and Hashcode () two methods and tell them that the two objects are hashcode the same, but they may not be equal. Some interviewers may give up, while others can move on, they answer "because the hashcode is the same, they have the same bucket position and the ' collision ' will happen." Because HashMap uses a linked list to store objects, this entry (Map.entry object with key-value pairs) is stored in the linked list. "The answer is very reasonable, although there are many ways to deal with collisions, this method is the simplest, and it is the hashmap approach." But the story is not over yet, the interviewer will continue to ask:

"If the two keys are the same hashcode, how do you get the value object?" The interviewer will answer: when we call the Get () method, HashMap uses the hashcode of the key object to find the bucket location and then gets the value object. The interviewer reminds him that if there are two value objects stored in the same bucket, he gives the answer: The list will be traversed until the value object is found. The interviewer will ask, because you don't have a value for the object to compare, how do you know for sure to find the value object? It is not possible for the interviewer to answer this question until HashMap stores the key-value pairs in the linked list.

Some of the interviewers who remember this important point of knowledge will say that after finding the bucket location, the Keys.equals () method is called to find the correct node in the list and finally find the value object to find. The perfect answer!

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.

If you think it's over, you'll be surprised to hear the following question. "What if the size of the hashmap exceeds the capacity defined by the load factor (payload factor)?" "Unless you really know how HashMap works, you won't be answering the question," he says. 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.

If you can answer this question, here's the question: "Do you understand what's wrong with resizing hashmap?" "You may not be able to answer the question, and the interviewer will remind you that in the case of multithreading, conditional competition (race condition) may arise.

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? :)

Enthusiastic readers have contributed more questions about HashMap:

    1. 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.
    2. 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.
    3. 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. You can see more articles about HashMap:

From

The difference between HashMap and HashSet

The difference between HashMap and HashSet is the most frequently asked question in the Java interview. If not involved in the collection framework and multi-threaded interview, can be said to be incomplete. The problem of collection framework is not related to HashSet and hashmap, it can be said to be incomplete. Both HashMap and HashSet are part of the collection framework, which allows us to work with collections of objects. Collection framework has its own interface and implementation, mainly divided into set interface, list interface and queue interface. They have their own characteristics, the set of the set does not allow the object has a duplicate value, list allows to repeat, it is the collection of objects indexed, the queue works as FCFS algorithm (first Come, first Serve).

First let's look at what is HashMap and hashset, and then compare the differences between them.

What is HashSet

HashSet implements the set interface, which does not allow duplicate values in the collection, when we refer to HashSet, the first thing is to ensure that the object overrides the Equals () and the Hashcode () method before storing the object in HashSet. This allows you to compare the values of objects to ensure that there are no equal objects stored in the set. If we do not override both methods, the default implementation of this method will be used.

The public boolean add (Object O) method is used to add elements to the set, which returns false immediately when the element value repeats, and returns True if added successfully.

What is HashMap

The HASHMAP implements the map interface, and the map interface maps the key-value pairs. Duplicate keys are not allowed in map. The map interface has two basic implementations, HashMap and TreeMap. TreeMap preserves the order in which objects are arranged, while HashMap does not. HashMap allow keys and values to be null. HashMap is non-synchronized, but the collection framework provides a way to guarantee hashmap synchronized, so that when multiple threads access HashMap at the same time, only one thread can change the map.

The public object put (object Key,object value) method is used to add elements to the map.

You can read this article to see how HashMap works, and this article looks at the difference between HashMap and Hashtable.

The difference between HashSet and HashMap

*hashmap*

*hashset*

HashMap implements the map interface

HashSet implements the set interface

HashMap Store key value pairs

Hashs Et only Stores objects

Use the put () method to place elements into a map

Use the Add () method to place the element in set

HashMap using the Key object to calculate the Hashcode value

HashSet uses member objects to calculate hashcode values, hashcode may be the same for two objects, so the Equals () method is used to determine the equality of objects, If two objects are different, then return false

HashMap faster because it is using a unique key to get the object

HashSet more slowly than HashMap

From

JAVA HashMap Knowledge Collation

Related Article

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.