HashMap finishing common interview questions

It took three days to read the source code hashMap carefully, fill knowledge during the next lot of data structure, brush a lot of questions related to the surface and finishing

1. Talk about the characteristics of the HashMap?

1.HashMap achieve fast access to store the key value, allowing to null. key value can not be repeated, if the key value is overwritten repeated.

2. asynchronous thread safe.

3. The bottom layer is a hash table, do not guarantee an ordered (such as the order of insertion)

 

2. What HashMap talk about the underlying principle?

Hashing based on the principle of the data structure used jdk8 list array + + red-black tree. We put and get to store and retrieve objects. When we pass to a key value and put () method, to make a pair of keys hashCode () is calculated to obtain its position in the array to store the bucket Entry object. When acquiring the object to get acquired by the position of the bucket, and then () method to find the correct key by key equals object, then the object in the return value.

 

3. hashMap talk about how to put in is achieved?

1. The value for the calculated hashcode of the key (16 bits of the XOR operation Key.hashCode)

2. If the hash table is empty, call resize () to initialize the hash table

3. If a collision does not occur to directly add elements to hash table

4. If a collision (the hashCode same value) occurs, for three kinds of determination

    4.1: If the key the same address or the same contents equals, then replace the old value

    4.2: If it is a red-black tree, the tree is called insertion method

    4.3: list structure, loops through the list until a node insertion is empty, the end of interpolation, it is determined whether the list after insertion of the number reaches the threshold into a red-black tree 8; nodes have to be traversed insertion element and the same hash value of the content, covered.

5. If the bucket is full is larger than the threshold, then the resize for expansion

 

4. hashMap talk about what time of the need for expansion, expansion resize () is how to achieve?

Recalling a scene:

1. Initialize Array table

2. When the size of the array table reaches threshold i.e. ++ size> load factor * when the capacity, but also in function putVal

Implementation :( go into detail)

1. determined by the capacity of the old array is greater than 0 to determine whether the initialized array

No: initialize

  • Determine whether to call no-argument constructor,
    • Is: Use the default size and threshold
    • No: Use constructor initializes capacity, of course, after the number of times the capacity of the power calculation tableSizefor 2

Is for expansion, expansion to double (at less than the maximum value), after performing the re-elements with copy operation to a new hash table

 

 

Speaking in general terms: expansion need to re-allocate a new array, a new array is twice the length of the old array, and then traverse the entire old structure, all the elements one by one to re-hash assigned to the new structure to go.

PS : visible underlying data structure uses an array, in the end because of capacity problems need to be operational expansion

5. hashMap talk about how to get in is achieved?

To key the hashCode were hashing, subscript and arithmetic calculation acquire bucket position, if it can be found on top of the barrel directly returned, otherwise find in the tree or linked list traversal to find, if there are hash conflict, using the equals method to traverse the list to find the node.

 

6. talk about a HashMap hash function is how to achieve? There are ways to achieve what hash function?

hashCode to do hash key operation, 16-bit high and exclusive ORing

There are middle-square method, except I stay, pseudo-random number method

 

7. Why not just as a hash value but the key XOR operation with 16-bit high?

Since operation is determined by the location of the array, only the last four significant, designer key hash value 16 is high so that the exclusive ORing & doing arithmetic determining the insertion position of the array, this time the actual low It is a combination of high and low, increasing the randomness, reduce the number of hash collisions.

 

HashMap default initialization length is 16, and in each case automatically or manually extended initial capacity, must be a power of 2.

 

8. Why 16? Why must be a power of 2? If the input value is not a power of 2 such as 10 what will happen?

https://blog.csdn.net/sidihuo/article/details/78489820

https://blog.csdn.net/eaphyy/article/details/84386313

1. For a uniform distribution of data, reducing the hash collision. Because the array to determine the position of the bit operation is used, if the data is not a power of 2 it will increase the number of waste and an array of space hash collision. (PS: In fact, without considering the efficiency, can I ask do not place the power of computing do not have the required length is 2)

2. If the input data is a power of 2, affirmative HashMap obtained through a shift operation by the OR operation, and the number is a power of 2, and recently from the digital number

 

9. talk about what happens when two objects are equal hashCode?

Will produce a hash collision, if the key value is the same as the old value is replaced, or link to the back of the list, the list is longer than the threshold into red-black tree stored on 8

 

10. If hashcode two keys are the same, how do you get the value of the object?

Same HashCode, obtain the value of the object by comparing the contents equals

11. "If the HashMap size exceeds the load factor (load factor) defined capacity, how to do?

Will exceed the threshold for expansion operations, general talk is the array size after expansion is 2 times the original array, re-hashing the original elements into the new hash table to go.

The difference 12.HashMap and HashTable

The same point: key are stored key-value pairs

difference:

  • Key-value allows the HashMap is null, hashTable allowed;
  • hashMap not consider synchronization, it is thread safe. hashTable is thread-safe, api to put a layer of synchronized modification;
  • HashMap class inherits from AbstractMap, hashTable inherit the Dictionary class.
  • Iterator (Iterator). HashMap iterators (the Iterator) iterator is fail-fast, and the enumerator Hashtable iterator is not fail-fast. So when there is another thread changed the HashMap structure (add or remove elements), will throw a ConcurrentModificationException.
  • And increasing the capacity of the initial values ​​are not the same manner: HashMap default capacity size is 16; increased capacity, the capacity becomes each "original capacity X2." Hashtable default capacity size is 11; increased capacity, the capacity becomes each "original capacity x2 + 1";
  • hash algorithm value added key-value different: HashMap elements are added, using a custom hash algorithm. Hashtable no custom hash algorithm, and direct use of the key of hashCode ().

 

13. Please explain HashMap of parameters loadFactor, what is its role?

loadFactor HashMap indicates the degree of congestion, the impact probability the same array position of hash to operate. The default loadFactor equal to 0.75, when the inside HashMap receiving element array has reached 75% HashMap length, expressed HashMap too crowded, capacity is needed, can be customized in the HashMap loadFactor constructor.

 

14. The shortcomings of traditional hashMap (Why the introduction of red-black trees?):

JDK 1.8 HashMap previously implemented is + arrays linked lists, hash function to obtain even better, it is difficult to achieve a uniform distribution element hundred percent. When a large number of elements in the HashMap are stored to the same bucket, there is a long chain under the barrel, this time is equivalent to a HashMap single chain, single chain if there are n elements, the time complexity is traversed O (n), completely lost its advantage. In view of this situation, JDK 1.8 introduced the red-black tree (lookup time complexity is O (logn)) to optimize this problem.

 

15. What is the usual type of element is generally used when using HashMap as a Key?

Select Integer, String immutable this type, as all the operations of the new String is a String object, the new object segmentation stitching, these classes have very standardized override the hashCode () and equals () method . As immutable class is inherently thread-safe,

 

Source analytic reading:

1.https://blog.csdn.net/u011240877/article/details/53358305#%E4%BC%A0%E7%BB%9F-hashmap-%E7%9A%84%E7%BC%BA%E7%82%B9

2. https://juejin.im/post/5ad40593f265da23750759ad

3. https://juejin.im/post/5afbff9451882542877353dd

4. https://blog.csdn.net/panweiwei1994/article/details/76555359#commentBox

5.

 

More about hashMap set of interview questions:

https://zhuanlan.zhihu.com/p/32355676

https://zhuanlan.zhihu.com/p/40760616

https://juejin.im/post/5a99544ef265da23a334ab6c

https://www.jianshu.com/p/7af5bb1b57e2

https://baiqiantao.github.io/Java/%E9%9B%86%E5%90%88/3AFbAb/

Guess you like

Origin www.cnblogs.com/zengcongcong/p/11295349.html