Java中有ImmutableBitSet吗?

maa*_*nus 11 java collections guava

是否有任何Java库提供ImmutableBitSet?我没有找到任何,也没有发现Guava也没有使用谷歌.

Jef*_*ter 6

你可以使用BigInteger,因为它有setBit,testBitclearBit.


maa*_*nus 4

我决定把所有答案总结一下:

我认为没有办法让一切变得完美,即获得 的不可变子类BitSet,以便equals以线程安全的方式工作。我承认我没有在问题中说出我的所有要求。

继承BitSet并让所有的 mutator 方法抛出异常既简单又有效。唯一的问题是,equals从自身调用BitSet不是线程安全的,因为它直接访问非最终继承字段。所有其他方法都可以通过下面描述的技巧变得线程安全。

委托给BitSet也很容易并且有效,唯一的问题是 aBitSet不能等于 an ImmutableBitSet。请注意,为了线程安全,委托必须存储在最终字段中。

将继承和委托结合起来看起来很有希望:

public class ImmutableBitSet extends BitSet {
    private final ImmutableBitSet delegate;

    public ImmutableBitSet(BitSet original) {
        or(original); // copy original to this
        delegate = this; // initialize a final reference for thread safety
    }

    @Override // example mutator method
    public void and(BitSet set) {
        throw new UnsupportedOperationException();
    }

    @Override // example non-mutator method
    public boolean get(int bitIndex) {
        return delegate.getPrivate(bitIndex);
    }

    // needed in order to avoid endless recursion
    private boolean getPrivate(int bitIndex) {
        super.get(bitIndex);
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

它看起来很奇怪,但工作起来近乎完美。调用bitSet.equals(immutableBitSet)不是线程安全的,因为它们直接访问非最终字段。所以这只是一次徒劳的练习。

BitInteger如果想要实现所有方法以及与可变 BitSet 之间的转换,则使用 a是一项相当大的工作。因此,我建议使用委托或继承,具体取决于所需的行为equals以及线程安全的需要。

  • 理想情况下,拥有 ImmutableBitSetBuilder 又名 Guava 风格会很好。无论如何,我向 Guava 提出了一个功能请求:https://code.google.com/p/guava-libraries/issues/detail?id=1059。如果您有兴趣,请投票。 (2认同)