Why must the capacity of the hash table if the integer power of 2?

First, Capacity is an integer power of 2, then calculate the position of the tub h & (length-1) modulo length is equivalent to improve the computational efficiency;

Second, capacity is an integer power of 2, then, is an even number, so capacity-1 is odd, odd last digit is 1, this will ensure the h last & (capacity-1) may be 0, is also likely to 1 (depending on the value of h), i.e., the result may be an even number, it may also be an odd number, so that they can ensure the uniformity of the hash;

And if capacity is odd, then, it is clear that capacity-1 is an even number, it's the last one is 0, so that h & (capacity-1) is the last one definitely is 0, that can only be an even number, so that any hash value only It will be hashed to an even position in the array index on which they wasted nearly half the space.

Excerpt: https://github.com/GeniusVJR/LearningNotes/blob/master/Part2/JavaSE/HashMap%E6%BA%90%E7%A0%81%E5%89%96%E6%9E%90.md

Thus, the capacity of the hash table taking an integer power of 2, the following two points advantages:

Alternatively subtraction modulo improve computational efficiency;
in order to make different the probability of collision of the hash value is smaller, causes the element as uniformly as possible hash in the hash table.
---------------------
Author: wipe Heart
Source: CSDN
Original: https: //blog.csdn.net/u011240877/article/details/53351188
Copyright: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/shujiying/p/11121753.html