简体   繁体   中英

Whats the list.size() equivalent of the BitSet?

My question would be better understood by the code below. I need to know how last bit set by me. How do I find it in bitset ?

public class FreeMain {

    FreeMain ( ) {  }

    public static void takeBitSet(BitSet bitSet) {
        // I intend to read 30 positions from bit set since the for loop looped from 0 to 29.
        // Just like list.size() would have given me number of elements added to it
        // whats the "list.size()" equivalent for bitset ? 
    }

    public static void main(String[] args) throws IOException {
        BitSet bs = new BitSet();
        System.out.println(bs.length());

        for (int i = 0; i < 30; i++) {
            bs.set(i);
            System.out.print(bs.get(i));
        }

        takeBitSet(bs);
    }  
}

There's cardinality() , which returns the number of bits that are set.

There's also length() , which returns 1 + the index of the highest bit set.

And there's size() , which returns the capacity, in bits, of the set.

Of those three length() - 1 is the closest thing to the "last bit set by you", but note that it is the index of the highest set bit, not the index of the most recently set bit (which is not possible using only BitSet ).

You also mentioned "number of elements added to it", for which cardinality() is the closest match (as long as you don't consider setting a bit to 0 to be semantically equivalent to "adding a 0 to the set").

I wasn't quite sure what the answer was (Jason C's is great). I threw together a tiny test to get a feel for it though (Java 7, 64-bit system):

import java.util.BitSet;

public class BitSetTest {
    public static void main(String[] args) {
        BitSet bset = new BitSet();

        for (int i = 0; i < 65; i++) {
            bset.set(i);
        }

        bset.set(78);

        System.out.println("Cardinality = " + bset.cardinality());
        System.out.println("Size = " + bset.size());
        System.out.println("Length = " + bset.length());
    }
}

Output:

Cardinality = 66
Size = 128
Length = 79

In this setup, you can take size to mean the amount of bits the set has available. (which increases when you exceed the initial size). Cardinality is the actual amount of elements that have been set so far. Length is the highest bit that was set, which you can see was 79, and the bits between may or may not have been set (depending on how the set was used prior).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM