首页 >> 大全

学习BitSet集合中set方法的小结

2023-07-03 大全 55 作者:考证青年

保存的是一个对应位置的布尔值,内部采用的是long类型的数组进行实现。那么它就是如何实现快速定位到对应的元素呢,我们对于源码进行分析,就可以见一二。

首先,打开的源码,查找到有一个属性值long[] words

    /*** The internal field corresponding to the serialField "bits".* 内部的字段类似处理连续的“位”*/private long[] words;

内部的元素的布尔值是利用bit进行表示的,在数组当中,一个long的值就代表的是64个布尔值。在内部定义了常量的信息:

    /** BitSets are packed into arrays of "words."  Currently a word is* a long, which consists of 64 bits, requiring 6 address bits.* The choice of word size is determined purely by performance concerns.* BitSets 被存储在数组words中。一个word是一个由64个bit组成的long值,需要6位地址位(64 = 2^6)* word的大小选择由性能决定。*/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;

在java的源码中,大量使用到位运算,在性能上有明显的优势,推荐一本关于位运算的书《’s 》,Java源码中很多地方的位运算都是源自该书。

java中set和get方法_学习七律冬云的学习小结_

继续正题,下面来看下在set值的时候是如何对应到bit位置,在代码中有对应的注释信息:

    /*** Sets the bit at the specified index to {@code true}.** @param  bitIndex a bit index* @throws IndexOutOfBoundsException if the specified index is negative* @since  JDK1.0*/public void set(int bitIndex) {//小于0直接报错if (bitIndex < 0)throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);//计算当前bitIndex所在的long数值的位置int wordIndex = wordIndex(bitIndex);//bitIndex的值大于现有的长度,则进行扩容expandTo(wordIndex);//此处位关键的点,在进行 << bitIndex的时候,可以直接定位到对应的位置words[wordIndex] |= (1L << bitIndex); // Restores invariantscheckInvariants();}

对于**(1L

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了