Home > Back-end >  Why HashMap disturbance of hashcode computed when calculating the indexFor, not directly return h
Why HashMap disturbance of hashcode computed when calculating the indexFor, not directly return h

Time:09-30

HashMap have two source hash and indexFor
1. Hash source is the key of hashcode perturbation calculation, main is to prevent different hashcode high is different, but the same low, lead to hash conflict, it is the key of hashcode and own high 16 exclusive or operation
2. IndexFor calculation can be the key position in the array h& (length)

Question 1: why only with its high 16 exclusive or, I know a HashMap has a capacity of two powers, but are limited to 2 of 16 power is why
Problem two: since the disturbance function have been largely solved the conflict of the hash, why not when calculating the key position in the TAB array directly in the hash value after the disturbance, but also let h and length 1 and operation

The main problem is now that you have the key of hashcode perturbation operation, make its more hash, why when inserted into the array does not directly use the hash value, because not enough hash?

CodePudding user response:

You can try to freely letter strings using HashMap intimdating crowd scenes like a hash () method to calculate the hash value after the disturbance, not small, if direct use of the hash value as an array subscript after disturbance, that requires the length of the array is large enough. Such as the demo below.
 
Public static void main (String [] args) throws InterruptedException {
String a="a".
String d="demo";
String e="ABC";
Int aHashcode=a.h ashCode ();
Int dHashcode=d.h. ashCode ();
Int eHashcode=e.h ashCode ();
System. Out.println (aHashcode ^ (aHashcode & gt;> 16));//output 97
System. Out.println (dHashcode ^ (dHashcode & gt;> 16));//output 3079629
System. Out.println (eHashcode ^ (eHashcode & gt;> 16));//output 96355

}

CodePudding user response:

H& (length) is the optimization of division took over, your map of length N, you store location must also can only be as between 1 to N
  • Related