0

I'm trying to Populate an array of BitSets with information about an int array

    //ar is a SIZE*SIZE 1-D int array, SIZE is a constant

    //decare BitSet array
    BitSet bs[] = new BitSet[SIZE];

    //initialize BitSet array
    for (BitSet x:bs)
        x = new BitSet();

    //populate BitSet array
    for (int i = 0 ; i < ar.length ; i++)
        if (ar[i] > 0)
            bs[(i/SIZE)].set(SIZE-(i%SIZE));

The last line is what seems to be the problem but I can't see anything wrong with the logic. Any ideas?

To make this a bit more clear, if I had an array like 0,3,4,5,0,1,0,0,1,2,7,0,2,3,0,3,2,0,0,0,2,1,5,8,0,0,0,0,0,1,0,0,0,6,0,0

I want to get a bitset array that could be represented as 011101,001110,110110,001111,000001,000100

1279343
  • 100
  • 8
  • 4
    Your initialization technique is wrong. Check [this question][1] for details. [1]: http://stackoverflow.com/questions/2556419/initializing-an-array-in-java-using-the-advanced-for-each-loop – gkuzmin Nov 16 '12 at 09:21

3 Answers3

7

You're problem is a miss understanding of the enhanced for loop. Basically:

for (BitSet x:bs)
    x = new BitSet();

Is just a piece of syntatic sugar. The compiler expands it to the following:

for (int i = 0; i < bs.length; i++) {
    BitSet x = bs[i];
    x = new BitSet();
}

In this expansion it's quite clear that you're simply assigning the new bit set to x and throwing it away. You're not actually modifying the array at all. You need to initialize the array as follows:

for (int i = 0; i < bs.length; i++) {
    bs[i] = new BitSet();
}
EdC
  • 2,309
  • 1
  • 17
  • 30
3

In java your 'foreach' construct works like this:

for (BitSet x:bs)
  x = new BitSet();

// is the same as:

for (int i = 0; i < bs.length; i++) {
  BitSet x = bs[i];
  x = new BitSet();
}

Your problem is you don't assign back to array, and there is no way to do it with 'foreach' construct. You have to use plain 'for' loop:

for (int i = 0; i < bs.length; i++) {
  bs[i] = new BitSet();
}
MBO
  • 30,379
  • 5
  • 50
  • 52
1

You are assigning the newly created object to a temporary variable x

Try something like below..

        int i=0;
        for (BitSet x:bs)
            {
                x = new BitSet();
                bs[i++] = x; //This will initialize the array elements
            }
Shashank Kadne
  • 7,993
  • 6
  • 41
  • 54
  • shouldnt it be bs[i] rather than bs[i++]?? – PermGenError Nov 16 '12 at 09:38
  • 2
    @GanGnaMStYleOverFlowErroR he has to increment i somehow, since he's not incrementing it in the for, it either needs to be i++ in the array assignement or as another line in the block. Since i++ is post increment this code does work. – EdC Nov 16 '12 at 09:42