2014-01-10 80 views
1

當我讀到關於java中的BitSet類時,我遇到了下面的例子。是BitSet類的邏輯,還是& xor與邏輯門邏輯相同?java中的BitSet類

有人可以請解釋我如何或方法在上面的例子中工作?因爲當我在有關Oracle文檔或方法來讀取它說::

公共無效或(BitSet中設置)

對此位與位set參數的邏輯OR。該位集被修改,以便當且僅當它已經具有值true或者位設置參數中的相應位具有值true時,其中的位具有值true。

參數:設置 - 位設置

下面是代碼::

import java.util.BitSet; 

public class BitSetDemo { 

    public static void main(String args[]) { 
    BitSet bits1 = new BitSet(16); 
    BitSet bits2 = new BitSet(16); 

    // set some bits 
    for(int i=0; i<16; i++) { 
     if((i%2) == 0) bits1.set(i); 
     if((i%5) != 0) bits2.set(i); 
    } 
    System.out.println("Initial pattern in bits1: "); 
    System.out.println(bits1); 
    System.out.println("\nInitial pattern in bits2: "); 
    System.out.println(bits2); 

    // AND bits 
    bits2.and(bits1); 
    System.out.println("\nbits2 AND bits1: "); 
    System.out.println(bits2); 

    // OR bits 
    bits2.or(bits1); 
    System.out.println("\nbits2 OR bits1: "); 
    System.out.println(bits2); 

    // XOR bits 
    bits2.xor(bits1);e 
    System.out.println("\nbits2 XOR bits1: "); 
    System.out.println(bits2); 
    } 
} 

The Output of above program is 

Initial pattern in bits1: 
{0, 2, 4, 6, 8, 10, 12, 14} 

Initial pattern in bits2: 
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14} 

bits2 AND bits1: 
{2, 4, 6, 8, 12, 14} 

bits2 OR bits1: 
{0, 2, 4, 6, 8, 10, 12, 14} 

bits2 XOR bits1: 
{} 

so in the above example result of or should be {0,1,2,3,4,6,7,8,9,10,11,12,13,14} according to oracle docs instead of {0, 2, 4, 6, 8, 10, 12, 14}. or am I misunderstood the explanation? 

Really appreciate the help. 

回答

0

的問題是,你計算bits2.or(bits1)bits2and電話已修改的值。不要直接在bits2上撥打or,andxor,請嘗試爲每個測試使用單獨的bits2副本。

+0

太感謝你了。我覺得不力在所有ABT修改BITS2 ..謝謝.. – Myrna

0

通過調用bits2.and(bits1)and操作期間bits2的值已被更改。 BITS2的值由以下orxor操作再次改變由呼叫bits2.or(bits1)bits2.xor(bits1)