BitSet保存的是一个对应位置的布尔值,内部采用的是long类型的数组进行实现。那么它就是如何实现快速定位到对应的元素呢,我们对于源码进行分析,就可以见一二。
首先,打开BitSet的源码,查找到有一个属性值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的大小选择由性能决定。
*/

本文主要探讨Java中的BitSet类,其利用long数组存储布尔值,每个long代表64个位。BitSet的set方法通过位运算快速定位并设置值。在set方法中,1L << bitIndex用于定位bit位置,当bitIndex超过64时,会有特定处理。文章建议阅读《Hacker’s Delight》以深入理解位运算,并提供了一个bitSet.set(128)的例子来说明操作过程。
最低0.47元/天 解锁文章
101

被折叠的 条评论
为什么被折叠?



