Dunno 'is about English, but here is some code and sample output:
public static void main ( String[] args ) { int h = 0xffffffff; int h1 = h >>> 20; int h2 = h >>> 12; int h3 = h1 ^ h2; int h4 = h ^ h3; int h5 = h4 >>> 7; int h6 = h4 >>> 4; int h7 = h5 ^ h6; int h8 = h4 ^ h7; printBin ( h ); printBin ( h1 ); printBin ( h2 ); printBin ( h3 ); printBin ( h4 ); printBin ( h5 ); printBin ( h6 ); printBin ( h7 ); printBin ( h8 ); } static void printBin ( int h ) { System.out.println ( String.format ( "%32s", Integer.toBinaryString ( h ) ).replace ( ' ', '0' ) ); }
What prints:
11111111111111111111111111111111 00000000000000000000111111111111 00000000000011111111111111111111 00000000000011111111000000000000 11111111111100000000111111111111 00000001111111111110000000011111 00001111111111110000000011111111 00001110000000001110000011100000 11110001111100001110111100011111
So, the code breaks the hash function into steps so you can see what happens. The first shift of 20 xor positions with the second shift of 12 positions creates a mask that can flip 0 or more of the lower 20 bits of int. This way you can get some randomness inserted into the lower bits, which uses potentially more distributed higher bits. It is then applied via xor to the original value to add this randomness to the low-order bits. A second shift at 7 x positions or a shift at 4 positions creates a mask that can flip 0 or more of the lower 28 bits, which again leads to some randomness to the lower bits and to some of the more significant ones, using the capitalization of the previous xor which already examined some of the distributions in low bits. The end result is a smoother bit allocation through the hash value.
Since the hashmap in java computes the bucket index by combining the hash with the number of buckets, you need to have a uniform distribution of the least significant bits of the hash value in order to evenly distribute the entries in each bucket.
As for the evidence of the claim that this limits the number of collisions, I have no input. Also, see here for good info on creating hash functions and a few details on why xor of two numbers tends to randomly distribute bits as a result.
philwb Feb 17 2018-12-17T00: 00Z
source share