Summary of Map source interview questions

Summary of Map source interview questions

Map occupies a large part of the interview questions in the interview, of which HashMap is the main one. Some of these interview questions can be explained clearly, and some are difficult to explain.

One: Map overall data structure problems

1.1: Talk about the underlying data structure of HashMap

Answer: The bottom layer of HashMap is the data structure of array + linked list + red-black tree. The main function of the array is to facilitate quick search. The time complexity is O(1), the default size is 16, and the subscript index of the array is calculated by the hashcode of the key. The array element is called Node. When the hashcodes of multiple keys are the same, but the key values ​​are different, a single Node will be converted into a linked list. The query complexity of the linked list is O(n). When the length of the linked list is greater than or equal to 8 and the array When the size of is greater than 64, the linked list will be transformed into a red-black tree. The query complexity of the red-black tree is O(log(n)). Simply put, the worst number of queries is equivalent to the maximum depth of the red-black tree.

1.2: What are the similarities and differences among HashMap, TreeMap and LinkedHashMap?

Answer: The same point:

  1. All three will use red-black trees under certain circumstances;
  2. During the iteration, if the data structure of the Map is changed, ConcurrentModificationException will be reported;

difference:

  1. The data structure of ashMap is mainly an array, and the query is very fast. The data structure of TreeMap is mainly red-black tree. It takes advantage of the characteristics of red-black tree that is small on the left and large on the right to realize key sorting. LinkedHashMap adds a linked list on the basis of HashMap. The structure realizes two strategies of insertion sequence access and least access deletion;
  2. Because of the differences in the underlying data structure of the three Maps, the use scenarios of the three are different. TreeMap is suitable for scenarios that need to be sorted by key, LinkedHashMap is suitable for access in the order of insertion, or scenarios that need to delete the least accessed elements. We use the remaining scenarios. HashMap is enough, most of the scenarios in our work basically use HashMap;
  3. Due to the difference in the underlying data structure of the three maps, the api of the upper packaging is slightly different;
  4. HashMap is the same as the underlying hash algorithm of LinkedHashMap, TreeMap has no hash algorithm;

Two: HashMap source code details

2.1: How does HashMap expand?

Answer: When to expand:

  1. When put, the array is found to be empty, and the initial expansion is carried out. The default expansion size is 16;
  2. After the put is successful, when it is found that the size of the existing array is larger than the expansion threshold, the expansion is performed, and the expansion is twice the size of the old array;

The threshold for expansion is threshold. The threshold will be recalculated every time expansion. The threshold is equal to the size of the array * impact factor (0.75).

2.2: What to do when the hash conflicts?

Answer: Hash conflict refers to the situation where the hashcode calculation of the key value is the same, but the key value is different.

If there is only one element in the bucket or it is already a linked list, the new element is directly appended to the end of the linked list;

If the elements in the bucket are already linked lists, and the number of linked lists is greater than or equal to 8, there are two situations at this time:

  1. If the size of the array is less than 64 at this time, and the array is expanded again, the linked list will not be converted into a red-black tree;
  2. If the array size is greater than 64, the linked list will be converted into a red-black tree;

Here not only the number of linked lists is judged to be greater than or equal to 8, but also the size of the array is judged. The array capacity is less than 64. There is no immediate conversion. The guess is that the red-black tree occupies a lot more space than the linked list, and the conversion is also time-consuming, so When the capacity is small, the conflict is serious. We can try to expand the capacity first to see if we can solve the conflict problem by expanding the capacity.

2.2: Why should the linked list be transformed into a red-black tree when the number of linked lists is greater than or equal to 8?

Answer: When there are too many linked lists, the traversal may be time-consuming. Converting to a red-black tree can reduce the time complexity of the traversal, but converting to a red-black tree requires space and time-consuming cost of conversion. According to the calculation of loose distribution formula, under normal circumstances, the concept of 8 in the number of linked lists is less than one in ten million, so under normal conditions, the linked lists will not be converted into red-black trees. The purpose of this design is to prevent abnormalities. Under circumstances, for example, when there is a problem with the hash algorithm, and the number of linked lists is easily greater than or equal to 8, it can still be traversed quickly.

Extended question: When will the red-black tree become a linked list?

Answer: When the number of nodes is less than or equal to 6, the red-black tree will automatically be converted into a linked list. The main consideration is the space cost of the red-black tree. When the number of nodes is less than or equal to 6, traversing the linked list is also fast, so red-black The tree will become a linked list again.

2.2: When HashMap is put, what if the key already exists in the array and I don't want to overwrite the value? What should I do if I want to return to the default value when the value obtained is empty?

Answer: If the array has a key, but you don't want to overwrite the value, you can choose the putIfAbsent method. This method has a built-in variable onlyIfAbsent. If the built-in is true, it will not overwrite. The put method we usually use, the built-in onlyIfAbsent is false, which allows overwriting of.

When taking the value, if it is empty and you want to return to the default value, you can use the getOrDefault method. The first parameter of the method is key, and the second parameter is the default value you want to return, such as map.getOrDefault("2","0") , When there is no key 2 value in the map, it will return 0 by default instead of empty.

Three: Other Map interview questions

3.1: When DTO is used as the key of Map, are there any points that need attention?

Answer: DTO is a data carrier, which can be regarded as a Java class with many attributes. We can perform get and set operations on these attributes.

See what type of Map, if it is a HashMap, you must override the equals and hashCode methods, because when get and put, you need to use the equals method to determine the equality; if it is a TreeMap, DTO needs to implement the Comparable interface, because TreeMap will use the Comparable interface to determine the size of the key; if it is LinkedHashMap, it is the same as HashMap.

3.2: What is the meaning of LRU in LinkedHashMap and how is it implemented?

Answer: LRU, English full name: Least recently used, Chinese called Least Recently Used, in LinkedHashMap, it is also called Least Access Delete Strategy. We can set a certain strategy through the removeEldestEntry method to make the least visited element at the right time The principle is that at the end of the put method execution, LinkedHashMap will check this strategy, and if it meets the strategy, delete the head node.

The principle of ensuring that the head node is the least visited element is: when the LinkedHashMap gets, it will move the currently visited node to the end of the linked list. Slowly, the head node will be the least visited element.

3.3: Why it is recommended that all elements of TreeMap implement Comparable interface? But when the key is String, we don't have any extra work?

Answer: Because the bottom layer of TreeMap is to compare the size of two keys by sorting, it is recommended that keys implement the Comparable interface to develop the sort order you want, and String itself has implemented the Comparable interface, so when using String, We don't need extra work, not just String, other packaging types also implement the Comparable interface, such as Long, Double, Short, etc.

Four: Summary

Map's interview questions are mainly HashMap, and will ask a lot of source code things. TreeMap and LinkedHashMap mainly focus on functions and scenarios, as bonus items.
There are many types of Map interview questions, but as long as you understand the principles, no matter how many questions you change, the answer will be easier.

Guess you like

Origin blog.csdn.net/weixin_38478780/article/details/107927282