下面列出了java.util.BitSet#previousClearBit ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Given a BitSet, returns a random bit that is currently false, or -1 if all bits are true.
* NOTE: this method is not fair.
*/
public static final int randomUnsetBit(Random r, BitSet bits, final int max) {
// NOTE: don't forget, BitSet will grow automatically if not careful
if (bits.cardinality() == max+1) {
return -1;
}
final int candidate = TestUtil.nextInt(r, 0, max);
if (bits.get(candidate)) {
final int lo = bits.previousClearBit(candidate);
final int hi = bits.nextClearBit(candidate);
if (lo < 0 && max < hi) {
fail("how the hell did we not short circut out? card="+bits.cardinality()+"/size="+bits.size());
} else if (lo < 0) {
return hi;
} else if (max < hi) {
return lo;
} // else...
return ((candidate - lo) < (hi - candidate)) ? lo : hi;
}
return candidate;
}
@Override
public Range<T> rangeContaining(long key, long value) {
BitSet rangeBitSet = rangeBitSetMap.get(key);
if (rangeBitSet != null) {
if (!rangeBitSet.get(getSafeEntry(value))) {
// if position is not part of any range then return null
return null;
}
int lowerValue = rangeBitSet.previousClearBit(getSafeEntry(value)) + 1;
final T lower = consumer.apply(key, lowerValue);
final T upper = consumer.apply(key,
Math.max(rangeBitSet.nextClearBit(getSafeEntry(value)) - 1, lowerValue));
return Range.closed(lower, upper);
}
return null;
}