java 中 BitSet 的 nextClearBit() 是如何工作的?

How nextClearBit() of BitSet in java actually works?

BitSet中的这个方法class用于return设置为false的第一个位的索引

import java.util.BitSet;
public class BitSetDemo {
   public static void main(String[] args) {
      BitSet b = new BitSet();
      b.set(5);
      b.set(9);
      b.set(6);
      System.out.println(""+b);
      System.out.println(b.nextClearBit(5));
      System.out.println(b.nextClearBit(9)); 
     }
   }
 Output :
 {5, 6, 9}
 7
 10

在此代码中,6 设置在 9 之后,但它表明值是连续存储的((b.nextClearBit(5) returns 下一个值是 7)。那么,BitSet 如何存储这些值 ?

BitSet是一组。 (插入的)顺序无关紧要。该方法只是给出了下一个更高清除位的索引。

内部实现已在上一个问题中进行了说明。对于每种方法,您都可以检查来源。 (该代码可能包含晦涩难懂的 "bit bashing"(也可在 java.lang.Integer/java.lang.Long 中使用,可作为内部函数实现)。)

nextClearBit 的 javadoc 说:

Returns the index of the first bit that is set to false that occurs on or after the specified starting index.

您已将 5、6 和 9 设置为 true。也就是说从5开始,第一个设置为false的index是7。从9开始,第一个设置为false的index是10。根据你自己的输出也是返回的。

如果您想知道 BitSet 的工作原理和功能,请阅读其 Javadoc 并查看源代码。它包含在 JDK.

BitSet 使用位来存储信息,像这样:

         ╔═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╦═══╗
Bits:    ║ 0 ║ 1 ║ 0 ║ 0 ║ 1 ║ 1 ║ 0 ║ 0 ║ 0 ║ 0 ║ 0 ║
      ...╚═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╩═══╝
Position: 10   9   8   7   6   5   4   3   2   1   0

每当您使用 set(n) - 它 设置 相应位置的位。底层实现是一系列长整数——但是为了理解 API,将它想象成一长串位(0 和 1)就足够了,就像图中那样。如果需要,它会自行扩展。

当需要查找5之后的下一个清除位时,转到第5位,并开始查找,直到找到零。实际上,依赖于位操作技巧,实现要快得多,但同样,要理解 API,这就是你可以想象的方式。

您的问题表明您可能认为 b.nextClearBit(i) 的结果以某种方式受到不同位设置为 truefalse 的顺序的影响。 这是错误的,因为 BitSet 不记得给索引赋值的顺序。

next 表示 "next in the order of the indices" 而不是 "next in the order of having been values assigned".

b.nextClearBit(i) returns 大于或等于 i 的最小索引 j 其中 b.get(i) == false.