Interview required: the internal structure of HashMap

HashMap data structure

    HashMap is a very interesting structure. Its entire structure is an array + linked list structure (when there are too many elements in a linked list, it will be readjusted into a red-black tree, which is an improvement in version 1.7).

    Literally speaking, HashMap is a map, which is a collection of mapping properties. One of its main functions is to calculate the hash value of an object, and then directly find the object through the hash value.

    To find objects by mapping, the time complexity is O(1).

How HashMap stores data

    When creating a HashMap, if an Integer parameter is not passed to the constructor, the default size of the HashMap is 16, and the performance in the source code is as follows:    

/**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    This number will be used when doing hash grouping.

    When an object is put into the HashMap, that is, when put(key, value) is executed, the hash value of the put key object will be calculated first, and an int hash value will be obtained after the calculation is completed, and then passed This hash value performs the remainder operation on the capacity of this HashMap (as mentioned earlier, the default capacity is 16), which is done in java as follows:

(n - 1) & hash

    Among them, n is the capacity of HashMap, this operation is equivalent to hash%n. After getting the remainder, you get which slot in the array the object is to be placed in. After determining which slot to put it in, it will compare the put value with all objects in this slot using the equals method:

    1. If all objects are different from value, put this object at the end of the linked list 

    2. If there is an object equal to the value when traversing, then replace the incoming object with its same object

    After such a process, the placement of an object is completed. In this process, you need to pay attention to one thing: because it is grouped by hash and then stored by equals, if two objects are equal, they must be placed in the same slot of the array. An object appears twice, and all objects in the HashMap are processed according to the hash value obtained by the hash algorithm, so there is no order at all, and the same object cannot appear twice. So the following conclusions are drawn:

    If two objects are equal, they must have the same hash value, and objects with the same hash value are not necessarily equal. This is also what we need to pay attention to when we override the hashCode() method and equals() method of the object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325342381&siteId=291194637