[2020-03-21] face questions JDK1.7 and 1.8 HashMap What is the difference

JDK1.7 and 1.8 HashMap difference:

  1. Array + + list into a list or an array of black tree;

  Table 2. interpolation insert mode into the head end of the interpolation, it simply is the insertion, if there is an array element location, the new elements into an array 1.7, the original node to a new node as a subsequent node, traversal 1.8 list, the list of the last element to be placed;

  3. When inserting, 1.7 to judge whether additional capacity is needed, then insert, the first insert 1.8, and then determines whether to complete the insert expansion

  4. When expansion is required to re-hash 1.7 positioned at the location of the new array, using 1.8 simpler determination logic, the same position or the size of the capacity index + original old elements in the array;

 

the reason:

   1. hash prevent conflicts, the list is too long, the time complexity of O(n)reduced O(logn);

   2. Reverse interpolation because expansion of 1.7, the list will first interpolation will occur ring multithreaded environment;

A thread insert Node B, B are inserted into the thread, starts expansion capacity is not enough encountered, the hash again, place elements, using the first interpolation method, after the traverse to the node B into the head, thus forming a ring, as shown below below:

    

 

 

     1.7 expansion call transfer code as follows:

void Transfer (the Entry [] NewTable, Boolean the rehash) {
   int newCapacity = newTable.length;
   for (the Entry <K, V> E: Table) {
     the while ( null =! E) { 
      the Entry <K, V> Next = E. Next;
       IF (the rehash) { 
        e.hash = null == 0 e.key? : the hash (e.key); 
      } 
      int I = indexFor (e.hash, newCapacity); 
      e.next = NewTable [I]; / / A thread if this line to suspend execution, B thread starts expansion 
      NewTable [I] = E; 
      E = next;
    }
  }
}

 

    3. Why expansion of 1.8 times without re-hash can be positioned directly in the new location of the original node data it?

This is because the expansion is expanded to 2 times the original size of the array, the array is used to calculate the position of the mask just a high of more than 1, how to understand it?

Before expansion a length of 16, for calculating the (n-1) & hash binary n-1 is 0000 1111, the binary expansion 32 on a more high as 00,011,111.

& Because calculation is 1, and any number of & itself, it is divided into two cases, as follows: raw hashcode data of upper 4 bits of the upper and 0 is 1;

Fourth high is 0, the hash value again unchanged, the fourth bit is 1, again the hash value larger than the original 16 (the old capacity of the array)

 

 Reference blog:

  https://blog.csdn.net/zhengwangzw/article/details/104889549?depth_1-utm_source=distribute.pc_category.none-task&request_id=&utm_source=distribute.pc_category.none-task

Guess you like

Origin www.cnblogs.com/gabriel-y/p/12540672.html