BitSet vs boolean[]

Hi all,
I need to store a bunch of true/false values, and I am debating between BitSet and a simple boolean[] array. The length of the bits is between 1-1000 bits, and I need to have in memory several hundreds of these bit sets.
For my application, memory is a bit more important than speed. And my understanding is that using BitSet set would require much less memory. So, for any one with suggestions:
[1] How does BitSet store data internally (I assume much less memory than an array of booleans)
[2] How fast is BitSet? Are there any complexity issues or gotchas I should be aware of?
[3] On a slightly different issue, I assume that HashMap (in genearl) has constant time for determining the number of keyed values in the map, is this correct?
Thanks,
-Adam

A BitSet uses a bit per value, a boolean[] uses a byte per value.
Either way you are using up to 1000 x 500 (several hundred) or between 64K and 500K. How much memory can your program use? I doesn't sound like much is you are using a desktop.

Similar Messages

  • Using a BitSet object

    Hello !
    I would like to store into MySQL a BitSet object. I am able to only use a string to do that :BitSet subBS = new BitSet();
    String strSubSet = "";
    subBS = Fingerprinter.getFingerprint(mol, 2048, 6);
    strSubSet = subBS.toString();This string could be verry big comparred to the object itself (more than 5 ko).
    Is it possible to be more efficient to store this BitSet into MySQL ?
    Thank you for your help,
    Jean-Marie

    public class RLE {
        public static String compress(BitSet bs) {
            boolean state = bs.get(0);
            int count = 0, l = bs.size();
            String ret = Integer.toString(l, Character.MAX_RADIX) + "," + (state ? "1" : "0");
            for(int i = 0; i < l; i++) {
                if(bs.get(i) == state){
                    count++;
                }else{
                    ret += "," + Integer.toString(count, Character.MAX_RADIX);
                    count = 1;
                    state = !state;
            return ret + "," + Integer.toString(count, Character.MAX_RADIX);
        public static BitSet expand(String s) {
            BitSet ret = new BitSet(Integer.valueOf(a[0], Character.MAX_RADIX));
            String[] a = s.split(",");
            boolean state = a[1].equals("1");
            int idx = 0, t;
            for(int i = 2; i < a.length; i++) {
                t = Integer.valueOf(a, Character.MAX_RADIX);
    if(state)
    ret.set(idx, idx + t);
    idx += t;
    state = !state;
    return ret;
    So you can store your BitSet using [i]RLE.compress(subBS) then retrieve it later using RLE.expand(strSubSet).
    Hope this helps~
    Alex Lam S.L.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Understanding Bitset

    Greetings... I'm in the process of converting an encryption algorithm from Java to VB. but first I'd like to better grasp the concepts behind the Java routines.
    from what I can see, the java routines take in a string such as
    #58#54#58#42#50#
    and returns the string
    ~b#9#XZ?�a�X�
    JAVA:
    private void s(String s1)
    private final String b_java_lang_String_array1d_fld[] = { "LHKf24()", "..FWSqw1", "783vcSWr", "NSW%FGS3", "S834VS$!"};
      StringTokenizer stringtokenizer = new StringTokenizer(s1 + "#", "#");
            BitSet bitset = new BitSet(64);
            for(int i1 = 0; i1 < 5; i1++)
                BitSet bitset1 = a(b_java_lang_String_array1d_fld[i1].toCharArray());
                int j1 = Integer.parseInt(stringtokenizer.nextToken());
                for(int l1 = 0; l1 < j1; l1++)
                    bitset1 = a(bitset1);
                bitset.xor(bitset1);
            char ac[] = a(bitset, 8);
            for(int k1 = 0; k1 < 8; k1++)
                if(ac[k1] == 0 || ac[k1] == '\n' || ac[k1] == '\r')
                    ac[k1] = (char)(ac[k1] | 0x80);
            try
                a_java_io_DataOutputStream_fld.writeBytes("~b#9#");
                for(int i2 = 0; i2 < ac.length; i2++)
                    a_java_io_DataOutputStream_fld.write((byte)(ac[i2] & 0xff));
                a_java_io_DataOutputStream_fld.writeBytes("\n");
            catch(Exception exception)
                a(1);
    private BitSet a(BitSet bitset)
            BitSet bitset1 = new BitSet(64);
            boolean flag = false;
            for(int i1 = 0; i1 < 64; i1++)
                if(flag != bitset.get(i1))
                    bitset1.set(i1);
                flag = bitset.get(i1);
            return bitset1;
    private BitSet a(char ac[])
            int i1 = ac.length * 8;
            BitSet bitset = new BitSet(i1);
            for(int j1 = 0; j1 < i1; j1++)
                int k1 = j1 & 7;
                int l1 = j1 >> 3;
                if((ac[l1] & 0xff & 1 << 7 - k1) != 0)
                    bitset.set(j1);
            return bitset;
    private char[] a(BitSet bitset, int i1)
            int j1 = i1 * 8;
            char ac[] = new char[i1];
            for(int k1 = 0; k1 < j1; k1++)
                int l1 = k1 & 7;
                int i2 = k1 >> 3;
                if(bitset.get(k1))
                    ac[i2] = (char)(ac[i2] | 1 << 7 - l1);
            return ac;
        }I would like to produce the same effects in VB, but I'm having trouble grasping the concepts behind how it encrypts/decrypts the strings.
    is this some form of bitset conversion? or mere string/character shift conversion?
    another string passed through the function is
    #58#32#59#48#26#
    which returns
    ~b#20#��-Un��
    any ideas on this concept would be greatly appreciated.

    This looks like decompiled obfuscated code! If not then what wonderful method names!

  • A few java functions i dont understand.

    The following functions i need translated into VB6 i have tried so very hard to this but i cant figure it out so i was hoping the people here on the sun forums could possibly help me i thank anyone who can remotely help me with this problem.
    private BitSet a(BitSet bitset)
    BitSet bitset1 = new BitSet(64);
    boolean flag = false;
    for(int i1 = 0; i1 < 64; i1++)
      if(flag != bitset.get(i1))
      bitset1.set(i1);
      flag = bitset.get(i1);
      return bitset1;
      private BitSet a(char ac[])
      int i1 = ac.length * 8;
      BitSet bitset = new BitSet(i1);
      for(int j1 = 0; j1 < i1; j1++)
        int k1 = j1 & 7;
        int l1 = j1 >> 3;
        if((ac[l1] & 0xff & 1 << 7 - k1) != 0)
        bitset.set(j1);
        return bitset;
        private char[] a(BitSet bitset, int i1)
        int j1 = i1 * 8;
        char ac[] = new char[i1];
        for(int k1 = 0; k1 < j1; k1++)
          int l1 = k1 & 7;
          int i2 = k1 >> 3;
          if(bitset.get(k1))
          ac[i2] = (char)(ac[i2] | 1 << 7 - l1);
          return ac;
          private void n(String s1)
          boolean flag = false;
          String as[] = {"MNfw9809", "90981qFS", "412.Fdq.", "..13fS4.", "41!!vs%&"
          StringTokenizer stringtokenizer = new StringTokenizer(s1 + "#", "#");
          BitSet bitset = new BitSet(64);
          for(int i1 = 0; i1 < 5; i1++)
            BitSet bitset1 = a(as[i1].toCharArray());
            int j1 = Integer.parseInt(stringtokenizer.nextToken());
            for(int l1 = 0; l1 < j1; l1++)
              bitset1 = a(bitset1);
              bitset.xor(bitset1);
              char ac[] = a(bitset, 8);
              for(int k1 = 0; k1 < 8; k1++)
                if(ac[k1] == 0 || ac[k1] == &apos;\n&apos; || ac[k1] == &apos;\r&apos;)
                ac[k1] = (char)(ac[k1] | 0x80);
                try
                  a_java_io_DataOutputStream_fld.writeBytes("~b#" + 13 + "#");
                  for(int i2 = 0; i2 < ac.length; i2++)
                    a_java_io_DataOutputStream_fld.write((byte)(ac[i2] & 0xff));
                    a_java_io_DataOutputStream_fld.writeBytes("\n");
                    a_java_io_DataOutputStream_fld.flush();
                    return;
                  catch(Exception exception)
                    a(exception);
                    }- Brian

    briansykes wrote:
    Well i'm trying to convert this code, i didn't decompile it but the person who gave it to me might have i'm just trying to port it to Visual Basic 6 i figured the java forums would be a good place to start. It's a handshake code for a chat server just wondering if its possible to port to Visual Basic 6.Of course it's possible, but this is a Java forum. You want to write VB6 code, so you need to find a VB6 forum.

  • Conversion from BitSet to long

    Hi!
    I want to convert a BitSet to a number in long format, and it shouldn't be very complicated because BitSet uses an internal array of longs, but I don't know how to do it.
    Any idea?
    Thanks!

    platters wrote:
    Thanks so much!
    I always have a lot of problems with bits! In the reverse mode, that is, from long to BitSet, until now I do:
    long data      = ..
    String sd = Long.toBinaryString(data);and then I convert the String to BitSet, is that very few efficient??If you want only the first 64 bits, why are you using a BitSet anyway? Converting to and from a long all the time isn't very efficient. You can use the long itself as if it were a 64 bit set. A few getBit(long set, int bit) and setBit(long set, int bit, boolean value) methods are al you have to implement:
    boolean getBit(long set, int bit) { // get bit 'bit' from the set
       return (set&(1L<<bit)) != 0;
    long setBit(long set, int bit, boolean value) { // return the new set with bit 'bit' (un)set
       if (value)
          return set|(1L<<bit);
       else
          return set&~(1<<bit);
    }kind regards,
    Jos

  • Array of booleans

    I have an array of booleans defined as follows:-
    Boolean [] isComplete = new Boolean[noOfBooleans];What I am trying to do is to continue a loop till all the values of this array are set to true. What I have tried is
    do {
        for (int i = 0; i < isComplete.length; i++) {
            if(isComplete) {
    break;
    }while(true);
    but it would break if anyof these booleans is true and I am not sure how to put an && condition in there. Any help would be great.
    Edited by: LisaM on Nov 10, 2009 11:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    LisaM wrote:
    ^you are right, actually I am dealing with threads here, what I am trying to do is to start a number of independant threads, and as these threads complete set the isComplete boolean to true. But I am unable to check when all the threads have finished. If you want to wait for the thread to complete, as opposed to just knowing when they complete, use Thread.join:
    List<Thread> threadList = new ArrayList<Thread>();
    for (...) {
      Thread th = new Thread(...);
      th.start();
      threadList.add(th);
    for (Thread th : threadList) {
      th.join();
    // when we get here, all the threads we started are doneAs for your code, if you do decide to continue with your initial approach (fixing the code so it actually works, of course), I have a few suggestions.
    1. A busy-wait loop like that will kill performance. Use wait/notify or sleep so that test loop doesn't eat up all your CPU.
    2. You'll have to synchronize all access to the array, otherwise the testing thread may never see the writing threads' updates.
    3. You may want to use BitSet instead of an array. It seems a little cleaner to me, but it won't make any real difference. You'll still have to sync all access to it.
    Finally, depending one what you're really trying to do, you may find some of the tools in the java.util.concurrent packages easier to work with than this low-level threading stuff.

  • Element position in boolean array

    Hi,
    I have a boolean array, whose elements are initialized to false. For example,
    private boolean array[] = new boolean[10];Later on I set an element of the array to true. Let's say
    array[5] = true;My question is how can I get the integer position of the element whose value(s) is/are true? Is there a method that does this? I looked into Arrays class but couldn't find anything.
    Thanks in advance.

    blias wrote:
    I have a boolean array, whose elements are initialized to false...
    My question is how can I get the integer position of the element whose value(s) is/are true? Is there a method that does this? I looked into Arrays class but couldn't find anything.You might want to have a look at [url http://download.oracle.com/javase/6/docs/api/java/util/BitSet.html]BitSet. It has loads of stuff for doing anything your heart desires for a bunch of bits, including Boolean operations on combinations and what you want.
    Winston

  • From bit array (boolean[]) to int and back

    (First of, I have searched hi and low, and have only found bits to bytes examples.)
    Simple question folks, I hope.
    How to convert a boolean[] array to an int or Integer, and from an int to a boolean array?
    I wouldn't mind using BitSet instead of primitives if that would help, but that api also does not supply a quick toInteger or valueOfInteger method.
    Please advise.
    Thanks, nat.

    You could use the bitwise operators:
    http://java.sun.com/docs/books/tutorial/java/nutsandbo
    lts/bitwise.html
    Especially see the part about "flags".Am aware of that and indeed use this. However, sometimes a boolean array is more convenient or a must (using the "flags", my constants have to be 2,4,8,16,32,64,128...) and
    I am dealing with a class that already has constants from 1 thru 21, and I want to add on to that class a boolean per constant, to track stuff I am adding to that class.
    Anyhow, is it THAT complex to convert from a boolean array to an int?
    nat

  • Boolean matrix - Please Help

    Would anyone be able to help me out with code to create a boolean (1/0) for a GUI? Iam looking to use a matrix of up to 10 rows and columbs that would resize depending on an entered value. It would then be possible to use the mouse to click on each element within the matrix to make it a 1 or a 0. I would appretiate any help.

    yay !!!!
    import java.awt.*;
    import java.awt.event.*;
    import java.util.BitSet;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    * @author  Ian Schneider
    public class BooleanMatrix extends JPanel {
        BitSet bits;
        int w = 10;
        int h = 10;
        /** Creates a new instance of BooleanMatrix */
        public BooleanMatrix() {
            resizeMatrix(w,h);
            MouseUpdater updater = new MouseUpdater();
            addMouseListener(updater);
            addMouseMotionListener(updater);
        public boolean isSet(int x,int y) {
            return bits.get(idx(x,y));
        public void toggle(int x,int y) {
            bits.flip(idx(x,y));
        private int idx(int x,int y) {
            return x + y * w;
        public void resizeMatrix(int w,int h) {
            bits = new BitSet(w * h);
            this.w = w;
            this.h = h;
        public Dimension getPreferredSize() {
            return new Dimension(w * 10,h* 10);
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (int i = 0, ii = w; i < ii; i++) {
                for (int j = 0, jj = h; j < jj; j++) {
                    if (isSet(i,j))
                        g.setColor(Color.green);
                    else
                        g.setColor(Color.red);
                    g.fillOval(i * 10 + 2,  j * 10 + 2, 6,6);
        class MouseUpdater extends MouseInputAdapter {
            public void mouseClicked(MouseEvent me) {
                int x = me.getX() / 10;
                int y = me.getY() / 10;
                toggle(x,y);
                repaint();
            public void mouseDragged(MouseEvent me) {
                mouseClicked(me);
        public static final void main(String[] args) throws Exception {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
            f.getContentPane().add(new BooleanMatrix());
            f.pack();
            f.setLocationRelativeTo(null);
            f.show();
    }The rest of the exercises are left to the student :)

  • Problem With Booleans and Threads

    Since using the .stop() and .resume() properties of a thread are dangerous, I resorted to using Booleans....
    I can get it to stop just fine by setting "keepGoing" to false. That works...
    But when I set the boolean to true... nothing happens. I think the while loop is broken when I set it to false and can't be fixed when the boolean is set back to true.
    There's some deep process I'm not getting with while loops and/or threads.
    Thanks for any help. The first segment of code is what's wrong. Post if it would help to see the rest.
    class startUpdatingThread extends Thread {
          public void run() {
              System.out.println("THREAD STARTING TO RUN!");
            while (keepGoing == true) {
                if (keepGoing == true) {
                Long nextGoAbout = imgTime + 5000;//five seconds more
                if ( ((nextGoAbout - connection.getDate()) < 10000) ) {
                    getnewPicture();
                    imgCanvas.repaint();
    }

    Still a missing }, and you'll still fall out the end of the thread. Something like this:
    class StartUpdatingThread extends Thread
         private volatile boolean     keepGoing = true;
         public void run()
              System.out.println("THREAD STARTING TO RUN!");
              for (;;)
                   synchronized (this)
                        while (!keepGoing)
                             try
                                  this.wait();
                             catch (InterruptedException exc)
                   Long nextGoAbout = imgTime + 5000;//five seconds more
                   if ( ( (nextGoAbout - connection.getDate()) < 10000) )
                        getnewPicture();
                        imgCanvas.repaint();
         public void pause()
              this.keepGoing = false;
         public synchronized void unpause()
              this.keepGoing = true;
              notifyAll();
    }//<--end of StartUpdatingThread()

  • Boolean in a bean

    I have a bean which has a method called isValid() this method returns either true or false.
    public class MyBean{
    //other methods here.............
    public boolean isValid(){
                    //...SQL STATEMENT
              if(result.next())
                   return true;
                   return false;
    }in my JSP page if the method returns false I want to write:
    "Incorrect information entered"
    but if it's true it will say:
    "Information is correct"
    I know how to get properties using the <jsp:getProperty... />
    but not how to get a return value from a method.
    how can I do this in my JSP page?
    Thanks for any help

    yes, but what is the tag for it:
    <jsp:useBean id="test" class="myPackage.MyBean" />
    <jsp:getProperty name="test" Property="What goes here??" />
    Thanks for your help

  • Need to convert a string to boolean

    i have string true, false, i need to convert them to boolean, is it good to use String.equals(true/false) or is it good to use Boolean.valueOf(true/false)
    Regards,
    Surya

    See http://forum.java.sun.com/thread.jsp?forum=54&thread=455788&tstart=0&trange=30.
    Remember, '=' is assignment, '==' is equals...

  • Type def boolean button.

    hi, i'm korean.
    my english is it' too bad. that why i'm sorry.
    first i wanna make type def boolean button.
    it's not problem. but make triangle shape.
    happen problem. like that
    red box is notihing. but if i click there, that is change to true or false.
    i don't know how to make flexible area setting.
    plz help me
    GOOD
    Solved!
    Go to Solution.

    Here is one way to do what you are asking: link
    This thread has a VI (post # 12) that uses triangle butons that may be a good start for you.

  • BOOLEAN DEFAULT FALSE NOT NULL for key-column

    Hello,
    These statements show an unexpected behavior when a column is added to a table as 'BOOLEAN DEFAULT FALSE NOT NULL' and added afterward to the table's primary key column set:
    create table test_1 (a char(1))
    insert into test_1 values('A')
    alter table test_1 add b boolean default false not null
    alter table test_1 add primary key (a,b)
    create table test_2 (a char(1), b boolean default false not null)
    insert into test_2 (a) values('A')
    alter table test_2 add foreign key f_test_1 (a,b) references test_1 (a,b)
          -> [350]: Referential integrity violated
    update test_1 set b=false
    alter table test_2 add foreign key f_test_1 (a,b) references test_1 (a,b)
          -> success
    delete from test_2
    delete from test_1
    insert into test_1 (a,b) values('A',false)
    insert into test_2 (a) values('A')
          -> success
    I think the error message '[350] Referential integrity violated' should not happen because the column 'b' really contains 'false'. But there obviously seem to be a difference before and after setting the column 'b' explicitly to 'false'. I can imagine that this depends on the way how the index for the primary key is updated. Probably the index is not properly updated in this context(?)
    Gabriel

    Hi Gabriel,
    you're right, this is a bug and indeed seems to caused by the way the DEFAULT boolean is stored in the page.
    (There is no separate index for the primary key in MaxDB as all data is stored in B*trees - basically the table is the primary key).
    This is how the record looks like when column b is 'false' only due to the change of the DEFAULT value:
    ROOT/LEAF 460  perm       entries : 1         [block 0]
         bottom  : 93         filevers: 14888     convvers: 83
                                                  writecnt: 1
      1: (pos 00081)
    00001      recLen      : 12                recKeyLen   : 4
    00005      recVarcolOff: 0                 recVarcolCnt: 0
         record
          1  2  3  4  5  6  7  8  9 10 11 12
         81 82 83 84 85 86 87 88 89 90 91 92
    dec: 12  0  4  0  0  0  0  0 32 65  0  0
    hex: 0C 00 04 00 00 00 00 00 20 41 00 00
    chr:                             A
    And this is how it looks like after the explicit UPDATE:
    ROOT/LEAF 460  perm       entries : 1         [block 0]
         bottom  : 93         filevers: 14888     convvers: 84
                                                  writecnt: 2
      1: (pos 00081)
    00001      recLen      : 11                recKeyLen   : 3
    00005      recVarcolOff: 0                 recVarcolCnt: 0
         record
          1  2  3  4  5  6  7  8  9 10 11
         81 82 83 84 85 86 87 88 89 90 91
    dec: 11  0  3  0  0  0  0  0 32 65  0
    hex: 0B 00 03 00 00 00 00 00 20 41 00
    chr:                             A
    Little difference but this leads to the problems during the foreign key validation.
    I'll inform the developers next week about this.
    As a workaround you'll have to explicitly update the columns for which you change the default setting.
    regards,
    Lars

  • Page Validation - Function Returning Boolean - Check for NULL

    I have 3 Page Validations which all fire on "When Button Pressed" = "Submit".
    <br><br>
    Number 1 is of type "Item specified is NOT NULL" for "P199_BUSINESS_UNIT1".
    <br>
    Number 2 is of type "Item specified is NOT NULL" for "P199_BUSINESS_UNIT2".
    <br>
    Number 3 is of type "Function Returning Boolean" and has the following code:
    <br><br>
    IF :P199_BUSINESS_UNIT1 IS NULL   AND
       :P199_BUSINESS_UNIT2 IS NULL  THEN
        RETURN FALSE ;
    ELSE
        RETURN TRUE  ;
    END IF ;<br>
    When P199_BUSINESS_UNIT1 is NULL and P199_BUSINESS_UNIT2 is NOT NULL, I get the Error from Validation 1. Perfect.
    <br>
    When P199_BUSINESS_UNIT1 is NOT NULL and P199_BUSINESS_UNIT2 is NULL, I get the Error from Validation 2. Perfect.
    <br>
    When P199_BUSINESS_UNIT1 is NOT NULL and P199_BUSINESS_UNIT2 is NOT NULL, I don't get an Error Message. Perfect.
    <br><br>
    When P199_BUSINESS_UNIT1 is NULL and P199_BUSINESS_UNIT2 is NULL, I get Error Message 1 & 2, <strong>but nothing from 3.</strong>
    <br><br>
    If I change the code to:
    <br><br>
    IF :P199_BUSINESS_UNIT1 = '01'   AND
       :P199_BUSINESS_UNIT2 = '01'  THEN
        RETURN FALSE ;
    ELSE
        RETURN TRUE  ;
    END IF ;<br>
    and change both values to '01', I get the appropriate Error Message.
    <br><br>
    What is going on? Is there some reason I can't check for NULL in a Function Returning Boolean?

    Scott,
    <br><br>
    Instead of adding the Validations, I changed my code from:
    <br><br>
    IF :P199_BUSINESS_UNIT1 IS NULL   AND
       :P199_BUSINESS_UNIT2 IS NULL  THEN
        RETURN FALSE ;
    ELSE
        RETURN TRUE  ;
    END IF ;
    <br>to the following and got the desired results:
    <br><br>
    IF  REPLACE(:P199_BUSINESS_UNIT1,<strong>'%null'</strong> || '%',NULL) IS NULL   AND
        REPLACE(:P199_BUSINESS_UNIT2,<strong>'%null'</strong> || '%',NULL) IS NULL  THEN
        RETURN FALSE ;
    ELSE
        RETURN TRUE  ;
    END IF ;<br>
    Note that I changed the word REPLACE to upper case and the second occurrence of the word NULL to upper case to accentuate the fact that the '%null' is case sensitive, using "%NULL' does not work, it has to be "%null' in lower case.
    <br><br>
    <strong>Thanks for your help.</strong>

Maybe you are looking for