HashMap how much you know

HashMap is almost the interview will ask knowledge, for HashMap interview is that you really can calmly face it? I believe if you go to the interview well-known Internet company, absolutely not just ask your HashMap data structure of such a simple question. I collected a few questions recently about the boss during the interview HashMap frequently asked:

1. Why HashMap is a power of 2?

new HashMap(14);

HashMap is an array + list (1.8 as well as red-black tree) is implemented, then the above line of code after it executes, the array size created is how much?
Tracking the source can see that it would perform such a function to return the array size:

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;
}

HashMap how much you know
Graphic:

  • The first or right shift operation and can guarantee a more back from left to right the first bit out of a 1
  • And a second or right shift operation, from left to right can be guaranteed two more 1
  • And so on, because the java int value is 4 bytes, 32-bit, 16-bit shift so the last time, sufficient to ensure this occurs 2 ^ 32;
  • By this calculation function, we pass 16 14 operation may be obtained, which is greater than the minimum of the n-th power of 2 14.

Described above will ensure that the final size of the array is the n-th power of 2, then the next talk about why you want to ensure that the n-th power of 2

 static int indexFor(int h, int length) {
     return h & (length-1);
 }

In jdk1.7 time, when put element for executing such a code fragment which is the data length intended hashCode value modulo operation. Since it was taken over, why not use it No.%? Because a lot of computing bit computing than% efficient.

Since that is the & operator, and why must ensure that length is 2 ^ n it?
HashMap how much you know

  • Length of 2 ^ n-1, it can result in & guarantee size range of the hash table;
  • % & Calculation result with the modulo may be consistent;

2. Why HashMap expansion factor is 0.75?

The load factor is a very important piece, if the load factor is too large, if 1, then from the space utilization actually up, but time efficiency is reduced.
If the load factor is too small, resulting in down hashmap frequent expansion of operations, each expansion are huge performance;
Okay! Like did not say, like to say, on this issue I can only initiate;
in fact, is this:

Because TreeNodes are about twice the size of regular nodes, we
 * use them only when bins contain enough nodes to warrant use
 * (see TREEIFY_THRESHOLD). And when they become too small (due to
 * removal or resizing) they are converted back to plain bins.  In
 * usages with well-distributed user hashCodes, tree bins are
 * rarely used.  Ideally, under random hashCodes, the frequency of
 * nodes in bins follows a Poisson distribution
 * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
 * parameter of about 0.5 on average for the default resizing
 * threshold of 0.75, although with a large variance because of
 * resizing granularity. Ignoring variance, the expected
 * occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
 * factorial(k)). The first values are:
 *
 * 0:    0.60653066
 * 1:    0.30326533
 * 2:    0.07581633
 * 3:    0.01263606
 * 4:    0.00157952
 * 5:    0.00015795
 * 6:    0.00001316
 * 7:    0.00000094
 * 8:    0.00000006
 * more: less than 1 in ten million

Select 0.75 is a compromise between space and time, but also not to say that non-essential 0.75, other programming languages ​​are also configured to 0.72.

3. jdk1.7 when expansion is how the cycle of death?

void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
           }
       }
   }

Speaking of this topic, then find a blog on the Internet to see is not really able to read, so I try to map a way to express
HashMap how much you know

It will produce an infinite loop when 4. jdk1.8 expansion?

Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
        next = e.next;
        if ((e.hash & oldCap) == 0) {
                if (loTail == null)
                        loHead = e;
                else
                        loTail.next = e;
                loTail = e;
        }
        else {
                if (hiTail == null)
                        hiHead = e;
                else
                        hiTail.next = e;
                hiTail = e;
        }
} while ((e = next) != null);
if (loTail != null) {
        loTail.next = null;
        newTab[j] = loHead;
}
if (hiTail != null) {
        hiTail.next = null;
        newTab[j + oldCap] = hiHead;
}

Look beneath the graphic analysis:
HashMap how much you know

So, in jdk1.8 HashMap when the expansion will not produce deadlock!

5. Why is the chain length reaches into red-black tree 8?

First, the size of the footprint is twice the TreeNode node list node only when the vessel reaches 8 when it turned red-black tree, 8 Why is it, in the second issue has been explained, according to the Poisson distribution see list node is difficult to achieve when the length of 8, should there be a special case of 8, then the list will only turn red-black tree;
turned red-black tree when there is a requirement that the elements hashMap number of 64.

6. jdk1.8 HashMap is thread safe?

JDK1.8HashMap even though it can do much to avoid infinite loop problem expansion, however, HashMap thread is still unsafe, for example: A thread when put elements, thread B for expansion;
the reason why is not safe for multithreaded operations will examples of variations of the same, resulting in inconsistent state variable;

Guess you like

Origin blog.51cto.com/13733462/2455435
Recommended