Created
March 27, 2015 01:25
-
-
Save ThomasLau/d89e127c04c164ed5616 to your computer and use it in GitHub Desktop.
HashMap里的tableSizeFor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 >= 1024) ? 1024 : n + 1; | |
} | |
这段方法,其实cap大于1024的时候,返回1024,这显然可以先放在开头的时候判断并直接返回的,不知道,hashmap为何要在最后。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这么做的道理是,
1,why先-1,首先是考虑到n本身是2的power,如63.
2,>>>1,然后再>>>2,>>>4,>>>8,>>>16,因为,假设n(!0)是 0_1+(0|1)_ 形式的,首先其首位是1,>>>1,保证自首位开始,至少前面2位是1,同理下去>>>2表示,前四位....