二次方取余技术在HashMap的应用

[size=medium] 取余计算对计算机来说是相对比较慢的,但是在许多场景下,例如循环队列指针的移动,hashmap的哈希操作都必须要做取余运算。

解决思路的大方向,其实跟用逻辑右移代替乘法一样(x*2 等价于 x << 1),也通过使用逻辑运算来替代取余。这里有一个规律,就是当N为2的次方(Power of two),那么X%N == X&(N-1)。

简单验证一下,设N=256,当X<=256,等式成立,当X>256,所有高位的部分都是256的倍数,高位部分被&屏蔽,相当于X转化为X-n*256,等式成立。

我们可以看看HashMap是如何运用这项技术的,首先HashMap通过算法过滤,使Hash表的容量保持为2的次方倍。[/size]

/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

[size=medium]当然也可以采用API简单的实现[/size]

/**
* Calculate the next power of 2, greater than or equal to x.<p>
* From Hacker's Delight, Chapter 3, Harry S. Warren Jr.
*
* @param x Value to round up
* @return The next power of 2 from x inclusive
*/
public static int ceilingNextPowerOfTwo(final int x)
{
return 1 << (32 - Integer.numberOfLeadingZeros(x - 1));
}

[size=medium]我们看到HashMap的容量使有符号的int型,所以很容易猜到,最大容量是2的31次方(最高位为符号位)。[/size]

/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

[size=medium] 假设容量为cap,key的hashcode为h,HashMap使用tab数组存放元素,元素在数组的下标位置index = tab[h&(cap-1)],我们看看核心的getNode方法实现[/size]

final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值