Container 48 (g) - HashMap bottom: hash algorithm and hash table structure

Hash table structure

+ Hash table is a linked list consisting of an array, there is a first array, each position in the array are used to store a list, the list of base node: [hash value, key value, value value, next], when stored when a key-value pair, the first call hashcode () method hashCode key is obtained, and then a hash value is calculated by the algorithm, when a different key to get the same hash value as a key behind a node connected to the same hash value to the previous the node key.

Algorithm hash value

Worst algorithm: hashcode / hashcode all the elements will be stored in an array subscript, it has actually reduced to an array

The algorithm used is : hashcode% array length

This algorithm obtained by [0, array length -1], i.e. hash values. This algorithm can be made as uniform as possible distribution of the respective key in the array. This table is also called a "hash (hash translation) table."

Optimization algorithms : the same is take the remainder, but is optimized. First agreed length of the array is an integer power of 2 , then quickly attain the hash value calculation by bit: hashcode & (array length -1)

Below about checking algorithm:

public class Test {
	public static void main(String[] args) {
		Test t = new Test();
		@ Algorithm: hashcode% the length of the array, assuming the array length (2 to the power 4) 16
		System.out.println(t.hashCode()%16);
		System.out.println(t.hashCode()&(16-1));
	}
}

result:
2
2

  

Followed by another optimized once, the hash algorithm is currently used (I do not understand):

get the underlying method

When calling the get method it will be passed by a key value, call hashCode () method to obtain a value corresponding hashCode, and then obtain the same hash value, and the bit bucket array (hash table is an array) by calculating a position corresponding to the list one by one equals comparison, the same as the return value.

equals hashCode method of comparison is a value, if a.equals (b) is true, then a and b has a value equal hashCode.

Expansion of the hash table

HashMap bit bucket array, the initial size of 16. When the bit array in the tub reaches an element (0.75 * array length), to re-adjust the size of the array is 2 times the original.

But expansion is very time-consuming.

When the bit bucket array list length is greater than 8, the list will be converted to a red-black tree, which will greatly improve search efficiency.

 

Guess you like

Origin www.cnblogs.com/Scorpicat/p/12021680.html