0

I have a function which takes as argument a BiSet object. I have the following

public static void(String [] args)
{
   BitSet test = new BitSet(15);

     Store(test);
}

public void Store (BitSet a)
{
  boolean [] temp = new boolean[a.length()]();
  System.out.println(temp.length);
}

The problem is that the length of my temp or a is 64. How can I get the actual length (15) of the object instance test that I passed to the function Store?

user3841581
  • 2,637
  • 11
  • 47
  • 72
  • Your `BitSet` probably does not have a length of 15 bits. [`new BitSet(15)`](//docs.oracle.com/javase/8/docs/api/java/util/BitSet.html#BitSet-int-) ensures that it can hold 15 bits. – bradimus Jul 22 '16 at 20:35
  • What is “actual length” and how is it different from length? A BitSet does not have a distinct size; it can only report the highest bit which is set. – VGR Jul 22 '16 at 20:35
  • yes but but when I have temp.length, I have 64 and not 15. I could have set the 10th bits but still want temp to have a length of 15 bits (I could set the others later) – user3841581 Jul 22 '16 at 20:36

1 Answers1

2

You can't. The constructor documentation says:

Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1.

There's no guarantee that the initial size won't be larger than the requested size. In fact, nbits is lost by the time the constructor completes.

But there's really no reason you should need the initial size in real code.

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • If that is not possible, is there any other data structure that I can use and on which I can apply (Set, OR, AND, XOR) efficiently (I am thinking about something like BitArray in C#) – user3841581 Jul 22 '16 at 20:41
  • @user3841581 you can use a simple `int` or `long`. But you won't get exactly 15 bits. It's still not clear why you would even want that. – shmosel Jul 22 '16 at 20:44
  • The issue is not getting 15 bits, it is having a Boolean array on which I can efficiently perform the operations I mentioned earlier in an efficient way – user3841581 Jul 22 '16 at 20:47
  • @user3841581 Then `BitSet` should do just fine. – shmosel Jul 22 '16 at 20:48
  • But I would like to keep a specific size, as I have some loops that are based on the length of the BitSet. That is my issue – user3841581 Jul 22 '16 at 20:50
  • @user3841581 so create a variable `int size = 15;` – shmosel Jul 22 '16 at 20:51