HashMap resolve common interview questions

HashMap underlying data structure?

Array + list, list + + array of red-black tree

HashMap access principle?

Calculated by obtaining a key object hashcode hash value of the object, by changing the hash value and the array length minus 1 bit AND operation (n-1 & hash), to give the position of the buckets, when the hash collision occurs, if value as the value of the old key value will be replaced, not the same value then the new list node, when the length of the list is more than 8, then converted into a red-black tree is stored.

Java7 and Java8 difference?

Create the object before jdk1.8, it creates a length of Entry 16 [] Table for storing key data. When not in the constructor after jdk1.8 created, but created only when the first call to put the method to create Node [] table, and then added in the list java7

Java7 when multi-threaded operating HashMap may cause an infinite loop, because invert the order of the list after the expansion of the transfer, modify the reference to the relationship between the original list of nodes in the transfer process.

Why will not thread safe?

Java7 when multi-threaded operating HashMap may cause an infinite loop, because invert the order of the list after the expansion of the transfer, modify the reference to the relationship between the original list of nodes in the transfer process.

Java8 does not cause an infinite loop in the same premise, the reason is the same before and after the expansion of the transfer order of the list, a reference node relationships before maintained.

But even if not an infinite loop, but through the source code to see put / get methods do not add synchronization lock, multi-threaded situation is most likely to occur: Can not guarantee the value of the last second put, the next second time or get the original value so thread-safety is not guaranteed.

HashMap will be resize (expansion) operation, recalculate the hash value, the resize operation time will cause the thread unsafe. The following places will give two threads may appear unsafe.

1, put the time of multi-threaded data inconsistencies caused.
This problem is better imagined, for example there are two threads A and B, A first index coordinate desirable to insert a key-value pairs to the HashMap calculated first recording to fall into the bucket, and then to obtain the list head inside the tub junction point, in this time slice thread a runs out, at which point the thread B is scheduled to be executed, and executed as thread a, B except thread successfully recorded into the inside of the tub, assuming a thread inserted recording calculated tub index and thread B record to be inserted bucket index is calculated from the same, then successfully inserted after thread B, thread a is scheduled to run again, it still holds an expired list head but knew nothing about it, so that it thinks it should do so, this way it covers the thread B inserted record, so thread B inserted record to suddenly disappear, resulting in inconsistent data behavior.

2, another obvious question is thread safe HashMap the get operation may cause an infinite loop because resize (cpu100%), that is a phenomenon linked list circular references (jdk7)

What are thread-safe class instead of it?

currentHashMap 以及 hashTable

The default initialization size? Why are so many? Why size is a power of 2?

The default size is 16 initialization The reason is this, if bucket bucket array initialization settings too, will be a waste of memory space, 16 is the size of a compromise, neither did put on a few elements such as 1,2,3 expansion , also did not like the tens of thousands you can only use a little bit of space so as to cause a lot of waste.

Size is a power of two is that when calculating the buckets of the bucket position, the formula is ((n-1) & hash), the end of a power of 2 minus 1 in the binary number is 1, with the hash value calculation , you will get the rest of the number. Bitwise AND operation result so that the remaining value of the object at the end of several hash values, so long as we hash hash value of the object to generate enough

The memory efficiency, minimize collisions, the ((n-1) & hash) index when seeking a more uniform

Array length is 2 n power

When the length of the array is not a power of 2, n

HashMap expansion mode? Load factor is how much? Why are so many?

Load factor is set to 0.75 instead of 1, because the set is too large, the greater will be the key to the chance of a collision bucket with a bucket position may be stored several value value, which increases search time, performance degradation , set too small nor appropriate if it is 0.1, then 10 barrels, threshold 1, you must put the two key-value pairs expansion, a waste of space.

What are the main parameters of the HashMap?

    //默认的map大小,为2的n次幂
    static final int DEFAULT_INITIAL_CAPACITY(默认初始容量) = 1 << 4; // aka 16

   // 最大容量,指定的值超过 2的30次幂,默认使用这个值
    static final int MAXIMUM_CAPACITY (最大容量)= 1 << 30;

   //在构造函数中没有指定时使用的负载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

   //当链表长度为8时,使用以红黑树代替链表,红黑树的结点是链表长度的两倍,当比较短的时候,使用红黑树的效率其实并不高,根据泊松分布公式的统计结果,在结点数达到8时,适合使用红黑树
    static final int TREEIFY_THRESHOLD(恐吓的阈值) = 8;
  
// 红黑树转为链表的阈值
    static final int UNTREEIFY_THRESHOLD (非恐吓的阈值)= 6;

//链表转红黑树时数组的大小的阈值,即数组大小大于这个数字时且链表长度大于8才会转为红黑树,
//在数组长度小于64,不会转,而是进行扩容
    static final int MIN_TREEIFY_CAPACITY = 64(小的恐吓容量);

HashMap is how to deal with hash collision?

If the same key, the content key corresponding to the most minimum value will be replaced, not the same key, to the back of the list, if the length of the chain length of 8 and reaches the array is greater than 64, then the linked list into a red-black tree, if the array less than 64, the expansion is performed

hash calculation rule?

The object hashcode () method returns a hash value, a 16-bit unsigned right shift, and with the original hash values ​​bitwise XOR operation, the aim is to hash the low and high 16bit 16bit made an exclusive OR, return values ​​to hash a sufficient

Get and put in the process, the index calculation, performs the hash operation hashCode firstly, and then calculate the hash value by a further standard, as shown below:

How to solve the initialization value, do not enter the n-th power of 2

    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

Objective: The binary values, the first occurrence of a start from left to right, all the values ​​on the right have become 1, making it possible to find out the n-th power than the current value of the freshman little number 2

When performing n >>> 16, which means that 32 bits will have carried out a bitwise OR, a

Guess you like

Origin www.cnblogs.com/chenhanhao/p/12469796.html