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

本文探讨了在HashMap中如何利用二次方取余技术提高效率。当哈希表容量为2的次方时,X%N可以转换为X&(N-1)。HashMap通过确保容量为2的幂,利用此技巧进行元素定位。文中详细分析了HashMap的tableSizeFor方法以及getNode方法,展示了如何在实际操作中应用这一技术。
摘要由CSDN通过智能技术生成

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

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

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

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

class="java" name="code">

/**

* 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;

}

当然也可以采用API简单的实现

/**

* Calculate the next power of 2, greater than or equal to x.

* 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));

}

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

/**

* 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;

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

final Node getNode(int hash, Object key) {

Node[] tab; Node 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)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、付费专栏及课程。

余额充值