用'与&'运算替代'取模%'运算

来源:互联网 发布:php对象的使用 编辑:程序博客网 时间:2024/04/25 20:10

a%b == a&(b-1),当b是2的指数时,等式成立。

由Java HashMap中,获取下标index的函数源码而发现。

static int indexFor(int h, int length) {
   return h & (length-1);
}