HashMap中的tableSizeFor()方法

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 21:03   4831   0

tableSizeFor(int cap)该方法用来返回大于等于该给定整数的最小2^次幂值;

用到的地方

public HashMap(int initialCapacity, float loadFactor);

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict);

private void readObject(java.io.ObjectInputStream s);

tableSizeFor()方法

static final int MAXIMUM_CAPACITY = 1 << 30;

static final int tableSizeFor(int cap) {
        int n = cap - 1;
        //相当于 n = n | n >>> 1
        //n >>> 1 右移一位
        n |= n >>> 1;
        System.out.println("n >>> 1 = " + n);
        n |= n >>> 2;
        System.out.println("n >>> 2 = " + n);
        n |= n >>> 4;
        System.out.println("n >>> 4 = " + n);
        n |= n >>> 8;
        System.out.println("n >>> 8 = " + n);
        n |= n >>> 16;
        System.out.println("n >>> 16 = " + n);
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

Test测试类

public class MapTest {

    public static final int MAXIMUM_CAPACITY = 1 << 30;

    public static void main(String[] args) {
       System.out.println(tableSizeFor(10));//16

    }

    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        //相当于 n = n | n >>> 1
        n |= n >>> 1;
        System.out.println("n >>> 1 = " + n);//13
        n |= n >>> 2;
        System.out.println("n >>> 2 = " + n);//15
        n |= n >>> 4;
        System.out.println("n >>> 4 = " + n);//15
        n |= n >>> 8;
        System.out.println("n >>> 8 = " + n);//15
        n |= n >>> 16;
        System.out.println("n >>> 16 = " + n);//15
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
}

转载于:https://my.oschina.net/u/3568600/blog/1926559

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP