Java BitSet,子集与交集

Java BitSet, subset vs intersection

我在 Java 中使用 BitSet class 来处理位集。 比较两个 BitSet 时,我需要明确区分 subset 的概念和 intersection.

的概念

让我们看一个使用 AND 运算符获取子集的示例:

    BitSet bits1 = new BitSet();
    BitSet bits2 = new BitSet();
    bits1.set(0,2,true); //110
    bits2.set(1);        //010
    //010 is a SUBSET of 110
    bits1.and(bits2);    //bits1 became the result of the and operator
    if(bits1.equals(bits2))
    {
        System.out.println(bits2 + " is a subset of " + bits1);
    }
    //PRINT

    BitSet bits4 = new BitSet();
    bits4.set(0,2,true); //110
    BitSet bits3 = new BitSet();
    bits3.set(1,3,true); //011
    bits4.and(bits3);
    //011 is NOT a subset of 110
    if(bits4.equals(bits3))
    {
        System.out.println(bits4 + " is a subset of " + bits3);
    }
    //NO PRINT

子集非常清楚,因为我使用 AND 运算符来验证一个 BitSet 是另一个的子集。

与内置交集运算符相同的示例:

    BitSet bits1 = new BitSet();
    BitSet bits2 = new BitSet();
    bits1.set(0,2,true); //110
    bits2.set(1);        //010
    //010 intersect 110, but is also a subset of 110
    System.out.println("Intersection? " + bits2.intersects(bits1));

    BitSet bits3 = new BitSet();
    bits3.set(1,3,true); //011
    //011 VS 110 intersection only
    System.out.println("Intersection? " + bits3.intersects(bits1));

这是我的问题:运算符交集同时检测子集和交集。 我的目标是仅检测交集,排除那些也是子集的交集,例如第二个示例中的 bits1 与 bits2。所以这个运算符不适合我的情况,因为它太笼统了。 有没有办法检测这个 属性?

取 bits1 bits2 和 bits1.and(bits2) 的基数。如果和基数不为零,则集合相交。如果它也等于 bits1 基数,则 bits1 是 bits2 的子集,反之亦然。

因此,使用基数,您可以根据需要检查子集关系(但它似乎并不比您在答案中已经提到的检查快多少,并且可以组合)。