2016-11-18 42 views
2

我使用Java中的BitSet類來處理位集合。 當比較兩個BitSet時,我需要明確區分子集交叉點的概念。Java位集,子集vs交集

讓我們看看使用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 

子集是很清楚,因爲我用的是和運營商能夠驗證是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。所以這個操作符不適合我的情況,因爲太籠統了。 有沒有辦法檢測到這個屬性?

回答

2

獲得bits1 bits2和bits1.and(bits2)的基數。如果和 - 基數不爲零,則這些集合相交。如果它也等於bits1基數,那麼bits1是bits2的一個子集,反之亦然。

因此,使用基數,只要你想,你可以檢查該子集的關係(但它似乎並不比你已經在你的答案中提到的檢查快得多,並可以結合)。