簡體   English   中英

為什么Java`BitSet`沒有`shiftLeft`和`shiftRight`函數?

[英]Why does Java `BitSet` not have `shiftLeft` and `shiftRight` functions?

是否有任何特殊原因導致這些缺失?

他們確實存在BigInteger ,但是由於不可改變的設計模式BigInteger這些通常非常緩慢。 BitSet更好,因為它是可變的,但我真的很想念shift函數( long s的<<>>> )。 對於BitSet ,就地移位也是有用的,以及循環旋轉。

我已經看到了對Shifting a Java BitSet的回復(使用get(off, len)進行移位;但這需要復制)。

別誤會我的意思。 我知道在哪里報告錯誤。 我只是想知道是否有一個特別的理由要省略它們,例如一些設計模式或這樣的概念。 特別是因為它們包含在BigInteger

從概念上講, BitSet通常/經常用於跟蹤許多設置,使得集合中的每個位具有特定含義。 因此,在這種情況下,輪班操作毫無意義。

您已經清楚地發現了BitSet另一個有用的用途,但它超出了BitSet可能設想的范圍。

我的猜測是它會讓一些代碼變得更復雜。 例如,如果你“向左移3”所有東西,你可以有一個額外的字段,移位,即-3(或者3,我只有50%的幾率使它正確:-)。 並且,對於get()和set()方法,如果您只是按shift調整bitIndex,則代碼應該有效。 例如

public boolean get(int bitIndex) {
    bitIndex += shift;  // new code!!!
    if (bitIndex < 0)
        throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);

    checkInvariants();

    int wordIndex = wordIndex(bitIndex);
    return (wordIndex < wordsInUse)
        && ((words[wordIndex] & (1L << bitIndex)) != 0);
    }

但是,對於某些其他操作,例如intersects()和or(),代碼將開始變得非常混亂。 現在,or()方法的核心非常簡單快速:

 // Perform logical OR on words in common
   for (int i = 0; i < wordsInCommon; i++)
      words[i] |= set.words[i];

   // Copy any remaining words
   if (wordsInCommon < set.wordsInUse)
     System.arraycopy(set.words, wordsInCommon,
                  words, wordsInCommon,
              wordsInUse - wordsInCommon);

如果兩個BitSets都有可能的轉換,這將很快變得混亂。 他們可能認為,如果你真的想轉移,你應該使用get和copy。

有一件事讓我感到驚訝 - 在get()中,他們沒有做1L << bitIndex&31 顯然是“循環,現在,我記得我的遠程機器語言,是有道理的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM