- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
- 4、该文档为VIP文档,如果想要下载,成为VIP会员后,下载免费。
- 5、成为VIP后,下载本文档将扣除1次下载权益。下载后,不支持退款、换文档。如有疑问请联系我们。
- 6、成为VIP后,您将拥有八大权益,权益包括:VIP文档下载权益、阅读免打扰、文档格式转换、高级专利检索、专属身份标志、高级客服、多端互通、版权登记。
- 7、VIP文档为合作方或网友上传,每下载1次, 网站将根据用户上传文档的质量评分、类型等,对文档贡献者给予高额补贴、流量扶持。如果你也想贡献VIP文档。上传文档
查看更多
Bitset分析
JAVA源码分析之BitSet
1.BitSet概述
BitSet实现了一种比特位的向量,能够自动增长,用途很广泛。如在bloom filter中会用到BitSet来标识某一位是否置位等。初始情况下所有位都为false。主要的变量如下表中所示,下面分析的时候会详细介绍这些变量的用处。首先可以注意到用来存储位向量的数组words为long类型,也就是说每一个值可以保存64位信息,所以ADDRESS_BITS_PER_WORD=6。变量wordsInUse用来表示当前有多少个words在用,初始为0,它的值在每次扩容words数组后更新,第一次调用set(int index)方法时一定会更新wordsInUse变量,因为初始值0会小于需要的words数目。这里的word都是long类型,即64位的。此外,变量sizeInSticky表示用户是否指定了words的数目。
private final static int ADDRESS_BITS_PER_WORD = 6;
private final static int BITS_PER_WORD = 1 ADDRESS_BITS_PER_WORD;
private final static int BIT_INDEX_MASK = BITS_PER_WORD - 1;
/**
* The internal field corresponding to the serialField bits.
*/
private long[] words;
/**
* The number of words in the logical size of this BitSet.
*/
private transient int wordsInUse = 0;
/**
* Whether the size of words is user-specified. If so, we assume the user
* knows what hes doing and try harder to preserve it.
*/
private transient boolean sizeIsSticky = false;
2.方法分析
BitSet()
public BitSet() {
initWords(BITS_PER_WORD); //BITS_PER_WORD=16=64
sizeIsSticky = false;
}
public BitSet(int nbits) {
// nbits cant be negative; size 0 is OK
if (nbits 0)
throw new NegativeArraySizeException(nbits 0: + nbits);
initWords(nbits);
sizeIsSticky = true;
}
private void initWords(int nbits) {
words = new long[wordIndex(nbits - 1) + 1];
}
/*判断指定比特位在数组中的索引,
*如第62位属于words[0],而第64位属于words[1](626=0, 646=1)
*/
private static int wordIndex(int bitIndex) {
// ADDRESS_BITS_PER_WORD=6
return bitIndex ADDRESS_BITS_PER_WORD;
} 由构造方法代码可知,当我们不指定比特数目时,则默认会用64来初始化BitSet,即words数组大小为1,并设置sizeIsSticky为false。如果指定了比特数目,则用指定的数目来创建words数组,并设置sizeInSticky为true。
set(int index):设置指定的第index位为true(其实就是置为1)。
public void set(int bitIndex) {
//判断bitIndex不能小于0
if (bitIndex 0)
throw new IndexOutOfBoundsException(bitIndex 0: + bitIndex);
//计算这一位在words数组中的位置
int wordIndex = wordIndex(bitIndex);
//判断是否需要扩展words数组大小
expandTo(wordIndex);
words[wordI
文档评论(0)