سؤال

I have been searching for this thing from past couple of days and came across the most recommended solution of using "BitSet method". I tried the same to set the index of bit and displayed it using get method.

Here's my code:

int value = (myMap.get(key));  // value could be anything from 0-255

if (items.contains(key)) {
    BitSet bitSet1 = new BitSet(256);

    bitSet1.set(value);
    System.out.print(bitSet1);

    for (int i5 = 1; i5 < bitSet1.size(); i5++) {
        boolean bit =  bitSet1.get(i5);
        System.out.print(bit?1:0);
    }
}

Problem is : as per the user operation there could be any value from 0-255 for example: 40,85,93

I want to set the respective bit index in the boolean array. Above code does set the respective index of bit to "1" but if there are indexes more than 1, the same number of boolean arrays get printed with respective bit.

I want to print the indexes of bits to "1" (as per the integer indexes in "value") in the same boolean array.

I played around with arraylist, int[] etc as well but couldn't be successful.

I know that some stupid thing is missing in the conceptual part but if you guys could help me out would be highly thankful.

هل كانت مفيدة؟

المحلول

It appears that the code snippet from your question is inside a loop that walks multiple values of the key variable, expecting all the bits that you set before the current iteration to be available during the current iteration as you go through the loop.

To address this problem you need to create the BitSet object prior to entering the loop, and keep re-using it, instead of creating it every time that you go through the if statement.

Move this line

BitSet bitSet1 = new BitSet(256);

to outside the loop that is implied in your snippet, or make it a variable in your class to fix the problem.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top