0

我有枚举;

enum testMe {
    one,
    two,
    three;

    long longValue() {
        return 1<<ordinal();
    }
}

for (testMe myLoop = testMe.values()) {
    System.out.println(value.longValue() + ":" + myLoop);
}

遍历枚举给了我对枚举中值的序数变化的期望。但是,我需要对我传入的参数进行限定;

Long myLong = 3;
for (testMe myLoop = testMe.values()) {
    if ((myLong & value.longValue()) != 0) {
        System.out.println(value.longValue() + ":" + myLoop);
    }
}

在这种情况下,只会打印一和二。但是,此方法仅适用于枚举中的 32 个值。有人知道如何使用 BigInteger 吗???

    BigInteger longValue() {
        BigInteger one = BigInteger.valueOf(1);
        return one.shiftLeft(ordinal());

谢谢 C

4

2 回答 2

2

使用EnumSet

EnumSet<TestMe> set = new EnumSet<>(TestMe.class);

EnumSet 具有您想要的位属性,但不幸的是并没有像long[]这样展示它们。否则使用BitSet.

于 2014-12-11T15:23:51.560 回答
2
  BigInteger b =BigInteger.ZERO;
  b = b.setBit( ordinal() );

您也可以使用 BigInteger.and(BigInteger x)。

enum OneTwo {
  one,
  two,
  three;

  BigInteger biValue() {
    BigInteger bi = BigInteger.ZERO;
    return bi.setBit(ordinal());
  }
  BigInteger biValue( BigInteger filter ) {
    BigInteger bi = BigInteger.ZERO;
    return bi.setBit(ordinal()).and(filter);
  }
}

和一个测试:

BigInteger three = BigInteger.valueOf(3L);
for (OneTwo ot: OneTwo.values()) {
    System.out.println( ot.biValue() + ":" + ot);
    System.out.println( ot.biValue(three) + ":" + ot);
}

打印没有问题。

或与零比较

if( BigInteger.ZERO.equals( bi.setBit(ordinal()).and(filter) ) ){
    // no bits in filter are set
}
于 2014-12-11T15:28:48.837 回答